2016-11-11 77 views
-1

如何按2列進行數據分組,但結果是1列(就像我們加入時一樣)。在mysql中按2字段分組

這是表 'jembatan'

id nama tahun jumlah 
----------------------------- 
1  A  2011  12 
2  B  2011  10 
3  A  2011  23 
4  B  2012  11 

我想要的結果是這樣的:

id totalA  totalB  tahun 
--------------------------------- 
     25   10   2011 
     0   11   2012 

如何做到這樣?

+0

通過開展基礎研究 – Strawberry

回答

1

你想有條件聚集:

select sum(case when nama = 'A' then jumlah else 0 end) as TotalA, 
     sum(case when nama = 'B' then jumlah else 0 end) as TotalB, 
     tahun 
from t 
group by tahun;