1

我需要做多个计数。我有大约 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

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

4

3 回答 3

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 ...
于 2013-07-31T13:49:14.620 回答
1

如果我了解您要做什么,我通常会这样做:

SELECT 
SUM(CASE WHEN Condition1 THEN 1 END) AS Column1,
SUM(CASE WHEN Condition2 THEN 1 END) AS Column2
FROM Contact
于 2013-07-31T13:47:57.627 回答
0

您需要运行子查询,或者至少这是一种方式:

SELECT
    ( SELECT COUNT(c.ID) FROM Contact c WHERE ... ) AS Column1,
    ( SELECT COUNT(c.ID) FROM Contact c WHERE ... ) AS Column2
于 2013-07-31T13:42:37.150 回答