按条件分组BY

时间:2014-10-06 17:18:29

标签: sql sql-server

我有以下方式的数据......

ColumnA ColumnB
7675    22838
7675    24907
7675    NULL

我希望结果如下.....

ColumnA ColumnB
7675    2  (need total count for Not Null value)
7675    0  (need count 0 for NULL value)

4 个答案:

答案 0 :(得分:4)

SELECT ColumnA, COUNT(ColumnB) ColumnB
FROM YourTable
GROUP BY ColumnA
UNION ALL
SELECT ColumnA, 0
FROM YourTable
WHERE ColumnB IS NULL
GROUP BY ColumnA

答案 1 :(得分:1)

您可以引入一个计算列,指明ColumnB是否为空,并将其与ColumnA一起用作分组标准:

SELECT
  t.ColumnA,
  ColumnB = COUNT(t.ColumnB)
FROM
  dbo.YourTable AS t
CROSS APPLY
  (SELECT CASE WHEN t.ColumnB IS NULL THEN 1 ELSE 0 END) AS x (SubGroup)
GROUP BY
  t.ColumnA,
  x.SubGroup
ORDER BY
  t.ColumnA,
  x.SubGroup
;

对于空子组,COUNT(t.ColumnB)表达式始终为NULL,对于相应的非空子组,它将返回非空条目的数量。

答案 2 :(得分:0)

select columnA, 
       count(columnB) as non_null_count, 
       sum(columnB is null) as null_count
from your_table
group by ColumnA

答案 3 :(得分:0)

如果有很多行而不是用UNION两次选择所有行,你可以轻松地使用计数和总和,这可能会更快。

SELECT columna, columnb, SUM(mycount) 
FROM
(   SELECT *, COUNT(columnb) as mycount 
    FROM test
    GROUP BY columnb
)t
GROUP BY mycount
ORDER BY CASE WHEN mycount = 0 THEN 1 ELSE 2 END DESC;

Fiddle Demo