使用SQL使用多个查询的多个SQL计数

时间:2013-07-31 13:38:33

标签: sql sql-server

我需要做多次计数。我有大约6列。像这样:

SELECT 
COUNT(C.ID) as 'Column 1',
COUNT(C.ID) as 'Column 2',
COUNT(C.ID) as 'Column 3',
COUNT(C.ID) as 'Column 4',
FROM CONTACT C

我需要能够使用不同的查询运行不同的计数,但不确定如何在一个结果中应用查询计数。

3 个答案:

答案 0 :(得分:2)

这里有几种选择。

1)使用子查询作为@TheSoultion提议

2)使用UNION

   SELECT 'A' NAME, COUNT(c.ID) [COUNT] FROM Contact c WHERE ... 
   UNION
   SELECT 'B' NAME, COUNT(c.ID) [COUNT] FROM Contact c WHERE ... 

3)如果它实际上是相同的子集但你想根据某些条件求和,那么在你的计数内使用用例

 SELECT sum(case ... when ... then 1 else 0 end) counta,
        sum(case ... when ... then 1 else 0 end) countb
 FROM ... WHERE ...

答案 1 :(得分:1)

如果我理解你要做的事情,我通常会这样做:

SELECT 
SUM(CASE WHEN Condition1 THEN 1 END) AS Column1,
SUM(CASE WHEN Condition2 THEN 1 END) AS Column2
FROM Contact

答案 2 :(得分:0)

您需要运行子查询,或者至少是单向运行:

SELECT
    ( SELECT COUNT(c.ID) FROM Contact c WHERE ... ) AS Column1,
    ( SELECT COUNT(c.ID) FROM Contact c WHERE ... ) AS Column2