2014-10-06 153 views
0

我有以下方式的數據....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) 

回答

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

我喜歡你將null和非null計數分隔到不同列的方式......這不會產生@jitendra所要求的結果,但它可以說比他/她想到的結果更好。 – evanv 2014-10-06 17:28:40

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

爲什麼使用聯合而不是/如果爲空? – evanv 2014-10-06 17:27:18

+1

@evanv因爲那不會返回所需的結果集 – Lamak 2014-10-06 17:28:20

+0

我沒有注意到列A的值是相同的。是的,拉馬克在這一點上是完全正確的。 – evanv 2014-10-06 17:33:16

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

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的空子組,並且對於相應的非空子組,它將返回非空條目的數量。