0

我有一个表名收据,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

谁能告诉我为什么它给我这个输出?

编辑

如果我想放置月份的名称而不是数字,那么该怎么做

4

3 回答 3

3

看起来你想要一个OR条件r.transaction_type='opening' and r.transaction_type='deposit'而不是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'

请参阅带有演示的 SQL Fiddle

或者您可以使用:

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')

请参阅带有演示的 SQL Fiddle

如果你想获得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)

请参阅带有演示的 SQL Fiddle

于 2012-11-08T11:16:42.570 回答
2

你在说

 ...r.transaction_type='opening' and r.transaction_type='deposit' 

r.transactiontype永远不会同时是“开放”和“存款”

于 2012-11-08T11:09:26.890 回答
0

我会将您的查询重写为

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

于 2012-11-08T11:16:41.837 回答