我想从按日期分组的下列表中选择数据
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查询来实现这种行为!
答案 0 :(得分: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 :(得分:1)
创建测试表后,我插入了一些记录,然后使用了这个查询:
select date_ as Date_Time, btype, sum(amount) as amount
from test
group by date_ , btype
答案 2 :(得分: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