我有以下方式的數據....GROUP BY
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)
我有以下方式的數據....GROUP BY
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)
select columnA,
count(columnB) as non_null_count,
sum(columnB is null) as null_count
from your_table
group by ColumnA
SELECT ColumnA, COUNT(ColumnB) ColumnB
FROM YourTable
GROUP BY ColumnA
UNION ALL
SELECT ColumnA, 0
FROM YourTable
WHERE ColumnB IS NULL
GROUP BY ColumnA
你可以很容易地做一個計數和總和,這可能會更快,如果有很多的行,而不是選擇所有的行兩次與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;
你可以引入一個計算列表示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的空子組,並且對於相應的非空子組,它將返回非空條目的數量。
我喜歡你將null和非null計數分隔到不同列的方式......這不會產生@jitendra所要求的結果,但它可以說比他/她想到的結果更好。 – evanv 2014-10-06 17:28:40