2017-02-02 63 views
0

我試圖寫一個簡單的SQL代碼,可以得到需要的結果,從這個表 -SQL Server的行數

原始表:

id | type 
123 0 
123 1 
123 1 
345 0 
345 0 

我試圖讓是:

id | zeroCount | oneCount 
123  1   2 
345  2   0 

我試圖group by的ID,也類型,但是,他們都給出了同樣的事情!

如何獲得所需的輸出?

回答

4

這裏有一個簡單的方法,假設值只有0和1:

select id, sum(1 - type) as zerocount, sum(type) as onecount 
from t 
group by id; 

更典型的方法是使用case(甚至pivot):

select id, sum(case when type = 0 then 1 else 0 end) as zerocount, 
     sum(case when type = 1 then 1 else 0 end) as onecount 
from t 
group by id; 
0

你可以得到看中並使用透視功能。但是,這將工作:

Select id, 
sum(case when type = 0 then 1 else 0 end) as ZeroCount, 
Sum(case when type = 1 then 1 else 0 end) as OneCount 
from table 
group by id 
order by id