singleapollo 2019-04-17 16:46 采纳率: 50%
浏览 237

oracle单表查询的问题

有一个流水明细表,字段有:部门(‘001’),日期(‘20190417’),金额(‘52462’)
我现在要查 各部门 2017,2018,2019年 每年的 合计金额,

我写的是

select a.部门, a.suma,b.sumb,c.sumc from
(select 部门, sum(金额) suma
from (select * from 表 where 日期 like '2019%')
group by 部门)a
left join
(select aab034, sum(金额) sumb
from (select * from 表 where 日期 like '2018%')
group by 部门)b
on a.部门 = b.部门
left join
(select aab034, sum(金额) sumc
from (select * from 表 where 日期 like '2017%')
group by 部门)c
on a.部门 = c.部门

但是这样太烂了,要是查每个月的话得left join 12次,求正确写法
  • 写回答

4条回答

  • GzlAndy 2019-04-17 17:03
    关注

    使用下面SQL再根据使用的数据库换一下处理日期格式的函数就可以了,我用的这个是mysql的

    select sum(money),dept,date_format(date,'%Y')
    from tail
    where dept in(10) and date_format(date,'%Y') in('2019')
    group by dept,date_format(date,'%Y')
    

    或者使用这个

    select sum(money),dept,sum(CASE date when  date_format(date,'%Y')='2019' then 1 ELSE 0 END)
    from tail
    where dept in(10) and date_format(date,'%Y') in('2019')
    group by dept
    
    
    评论

报告相同问题?