我有一张表名收据,scema如下所示
account_no date transaction_type amount
s1 2012-7-7 opening 500
s1 2012-8-13 deposit 1000
s1 2012-7-17 deposit 400现在我有了以下查询
select month(r.date),
sum(case when (month(r.date))='7' and r.transaction_type='opening' and r.transaction_type='deposit' then r.amount else '' end )as debit
from receipt r
where r.account_no='s1'但它给我的产出是:
month debit
7 0有人能告诉我为什么要给我这个输出吗?
编辑
如果我想把月份的名字而不是数字放在上面,那该怎么做呢?
发布于 2012-11-08 11:16:42
似乎您希望在r.transaction_type='opening' and r.transaction_type='deposit'之间而不是在AND之间设置一个AND条件。
select date_format(r.date, '%M'),
sum(case when (month(r.date))='7'
and (r.transaction_type='opening'
or r.transaction_type='deposit')
then r.amount else 0 end )as debit
from receipt r
where r.account_no='s1'请参阅与Demo
或者你可以使用:
select date_format(r.date, '%M'),
sum(r.amount)
from receipt r
where r.account_no='s1'
and month(r.date) = 7
and r.transaction_type in ('opening', 'deposit')请参阅与Demo
如果要获得所有月份的sum(),则需要添加一个group by
select date_format(r.date, '%M'),
sum(r.amount)
from receipt r
where r.account_no='s1'
and r.transaction_type in ('opening', 'deposit')
group by month(r.date);或
select date_format(r.date, '%M'),
sum(case when (r.transaction_type='opening'
or r.transaction_type='deposit')
then r.amount else 0 end )as debit
from receipt r
where r.account_no='s1'
group by month(r.date)请参阅与Demo
发布于 2012-11-08 11:16:41
我会重写你的查询
select month(r.date) as month,
sum(r.amount) as debit
from receipt r
where r.account_no = 's1'
and month(r.date) = 7
and (r.transaction_type = 'opening' or r.transaction_type = 'deposit');正如其他人已经指出的那样,将and更改为or。
https://stackoverflow.com/questions/13287827
复制相似问题