首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在sql中以月份为基础的借方总和

在sql中以月份为基础的借方总和
EN

Stack Overflow用户
提问于 2012-11-08 11:07:13
回答 2查看 118关注 0票数 0

我有一张表名收据,scema如下所示

代码语言:javascript
复制
account_no  date        transaction_type  amount
   s1       2012-7-7    opening           500
   s1       2012-8-13   deposit           1000
   s1       2012-7-17   deposit           400

现在我有了以下查询

代码语言:javascript
复制
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'

但它给我的产出是:

代码语言:javascript
复制
month  debit 
7      0

有人能告诉我为什么要给我这个输出吗?

编辑

如果我想把月份的名字而不是数字放在上面,那该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-08 11:16:42

似乎您希望在r.transaction_type='opening' and r.transaction_type='deposit'之间而不是在AND之间设置一个AND条件。

代码语言:javascript
复制
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

或者你可以使用:

代码语言:javascript
复制
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

代码语言:javascript
复制
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);

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2012-11-08 11:16:41

我会重写你的查询

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13287827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档