2016-10-20 99 views
-1

我有一個初學者問題。我的SQL表看起來像:SQL:多個選擇只有一個條件有所不同

| Date | Type | Manufacturer | 
2016/04/01 A   X 
2016/04/01 B   Y 
2016/04/02 B   X 
2016/05/07 A   Z 
    ...  ...  ... 

我的目標是計算兩個日期之間製造商「類型」的數量。我希望得到的結果類似以下內容:

| Manufacturer | Quantity_TypeA | Quantity_TypeB | 
    X    1     1 
    Y    0     1 
    Z    1     0 

我的查詢是這樣的:

select Manufacturer as Manufacturer, 
COUNT(*) as Quantity_TypeA 
From MyTable 
Where [Type] = 'A' and 
Date between '20150101' and '20160930', 
COUNT(*) as Quantity_TypeB 
From MyTable 
Where [Type] = 'B' and 
Date between '20150101' and '20160930'  
group by Manufacturer Order by Quantity_TypeA DESC 

我也試圖在使用類型的功能,如CASE,並沒有奏效。我錯過了什麼,但是什麼?

+0

好像你有某種日期格式不一致。列日期的數據類型? – jarlh

回答

2

試試這個

select Manufacturer as Manufacturer, 
SUM(case when [Type] = 'A' then 1 else 0 end) as Quantity_TypeA, 
SUM(case when [Type] = 'B' then 1 else 0 end) as Quantity_TypeB 
From MyTable 
Where 
Date between '20150101' and '20160930' 
group by Manufacturer 
+1

這是完美的! – Elhendriks

1

使用case表達式進行條件計數:

select Manufacturer as Manufacturer, 
     COUNT(case when [Type] = 'A' then 1 end) as Quantity_TypeA, 
     COUNT(case when [Type] = 'B' then 1 end) as Quantity_TypeB 
from MyTable 
where Date between '20150101' and '20160930', 
group by Manufacturer 
order by Quantity_TypeA DESC 

count()也只能算非空值。 case表達式返回1或null,即只有A或B被計數。