如何进行分组和计数场

时间:2015-02-23 12:33:17

标签: sql sql-server tsql count sum

我需要SumCounted的{​​{1}}。顺便说一句,我需要Grouped columns来了解具体情况。

这是我复杂的查询;

Where Clause

我只想知道我有多少行SELECT COUNT(id) AS Counted, State FROM Table1 GROUP BY State HAVING State NOT IN (2,3) UNION ALL SELECT SUM(Say) AS SubSUM, State FROM ( SELECT COUNT(b.id) AS SubCount, b.State FROM Table1 AS b GROUP BY b.State HAVING b.State IN (2,3) ) S GROUP BY S.State 2和3.我希望能解释。

1 个答案:

答案 0 :(得分:7)

我认为你可以通过条件聚合做你想做的事。像这样:

SELECT COUNT(id) AS total,
       SUM(CASE WHEN State NOT IN (2, 3) THEN 1 ELSE 0 END),
       SUM(CASE WHEN State IN (2, 3) THEN 1 ELSE 0 END)
FROM Table1;