2017-02-10 59 views
0

分組如何選擇SQL結果我想從按日期按日期

date  btype  amount 
1-2-2017 income  1000 
1-2-2017 income  200 
1-2-2017 Expense  100 
1-2-2017 Expense  200 

2-2-2017 income  1000 
2-2-2017 income  500 
2-2-2017 Expense  1000 

3-2-2017 income  2000 
3-2-2017 Expense  500 

下表組,以便我的結果應該是這樣選擇的數據。

date  Income  Expense 
1-2-2017 1200  300 
2-2-2017 1500  1000 
3-2-2017 2000  500 

請問一些機構指導我如何編寫SQL查詢來實現這種行爲!

回答

2

這是相當簡單的SQL,你應該能夠有點谷歌的找出自己:

select date 
     ,sum(if(btype = 'income', amount, 0)) as Income 
     ,sum(if(btype = 'expense', amount, 0)) as Expense 
from table 
group by date 
1

創建一個測試表後,我插入一些記錄,然後我用這個查詢:

select date_ as Date_Time, btype, sum(amount) as amount 
from test 
group by date_ , btype 
+0

請只需添加腳本和結果,你的問題文本。如果您需要格式化結果,請轉至https://ozh.github.io/ascii-tables/並粘貼您的SSMS輸出。 – iamdave

+0

請不要發佈圖片。 – Strawberry

1

另一種方法

select date 
     ,sum(case when btype = 'income' then amount else 0 end) as Income 
     ,sum(case when btype = 'expense' then amount else 0 end) as Expense 
from table 
group by date