2010-12-21 124 views
1

我正在嘗試創建SQL Select,它根據字段返回特定字段的計數。 所以,這是我想要做的。SQL Select for multiple where子句

Select count(distinct id) as TotalCount, -- this will be the total of id 
count(distinct id where type='A') as TotalA, -- this will be total when type='A' 
count(distinct id where type='B') as TotalB -- This will be total when type = 'B' 
from MyTable 

基本上TotalCount = TotalA + TotalB。

如何在SQL Select語句中實現此目的? 謝謝。

回答

5
Select count(distinct id) as TotalCount, -- this will be the total of id 
count(distinct case type when 'A' then id else NULL end) as TotalA, 
count(distinct case type when 'B' then id else NULL end) as TotalB 
from MyTable; 

當然TOTALCOUNT可能會或可能不會總量a +共計b,根據實際數據。

1

你能做到這樣的:每個類型

SELECT 
    count(distinct id) as TotalCount, 
    sum(CASE WHEN type = 'A' THEN 1 ELSE 0) as TotalA, 
    sum(CASE WHEN type = 'B' THEN 1 ELSE 0) as TotalB, 
FROM 
    MyTable 

計數:

SELECT 
    type, 
    count(DISTINCT id) 
FROM 
    MyTable 
GROUP BY 
    type 
+0

SUM(1)!= COUNT(DISTINCT) – 2010-12-21 23:55:15

+0

吧,我剛剛看了評論說: 「總」 – 2010-12-22 00:12:45

0

爲什麼不簡單UNION單獨的查詢。

Select 'all' as which, count(distinct id) as Total from mytable 
    union 
    select 'a' as which, count(distinct id) where type='A' as Total from mytable 
    union 
    select 'b' as which, count(distinct id) where type='B' as Total from mytable