使用mysql查询实现表格中的内容

img


请各位指教一下,
该如何查询出每个公司不同类型不同时间的合计值
最好是一条sql,多条也可以


select 
name,
type,
sum(case when y = 2020 then total else 0 end) as '前年总计',
sum(case when y = 2020 or y = 2021 or y = 2022 then total else 0 end) as '前年1-本月总计',
sum(case when y = 2021 then total else 0 end) as '去年总计',
sum(case when y = 2021 or y = 2022 then total else 0 end) as '去年1-本月总计',
sum(case when y = 2022 then total else 0 end) as '今年1-本月总计'
from (
 select name, type, year(date) as y,sum(value) as total from t group by name, type, y
) t 
group by name,type

自己上c查

首先得到 本年 去年 本年月 去年月 ,然后类似下面写法


select  * from (
select name,type  from tb group by name,type ) t left on 
(
select name,type,date,sum(value) 去年合计 from tb where year(date)=2021 group by name,type,date) t1
on t.name=t1.name and t1.type=t.type
left join (
select name,type,date,sum(value) 去年本月合计 from tb where year(date)=2022 group by name,type,date
) t2 on t2.name=t.name and t.type=t2.type
left join (
select name,type,date,sum(value) 今年合计 from tb where date=2021-07 group by name,type,date
) t3 on t3.name=t1.name and t1.type=t3.type
left join (
select name,type,date,sum(value) 今年本月合计 from tb where year(date)=2022-07 group by name,type,date
) t4 on t4.name=t.name and t.type=t4.type

金额太少

select
name,
type,
sum(case when y = year(SYSDATE()) - 2 then total else 0 end) as '前年总计',
sum(case when y = year(SYSDATE()) - 1 then total else 0 end) as '去年总计',
sum(case when y = year(SYSDATE()) - 2 or y = year(SYSDATE()) - 1 or (y = year(SYSDATE()) and m <= month(SYSDATE())) then total else 0 end) as '前年1-本月总计',
sum(case when y = year(SYSDATE()) - 1 or or (y = year(SYSDATE()) and m <= month(SYSDATE())) then total else 0 end) as '去年1-本月总计',
sum(case when y = year(SYSDATE()) and m <= month(SYSDATE()) then total else 0 end) as '今年1-本月总计'
from (
select name, type, year(date) as y,month(date) as m,sum(value) as total from t group by name, type, y
) t
group by name,type

望采纳,谢谢

完整的sql如下,一条sql可以解决,

select name,type,date,sum(value) from table
group by name,type,date

如有帮助,请采纳,十分感谢!

用 union all:比如这样,每个条件写一遍

SELECT * FROM USER WHERE user_id=1
UNION ALL
SELECT * FROM USER WHERE user_id=2
UNION ALL
SELECT * FROM USER WHERE user_id=3