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
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考