sql server每月数据求和

要求修改第二个SQL,完成第一个sql语句的效果
我的思路是判断数据库D.DYM的数据是否为空,为空则不显示每月和,不为空则显示,现在第2个sql语句就显示2.28一天的数据。


这个结果是正确的
sum(case when D.RQ BETWEEN '2022-01-01' and '2022-02-28' then d.ryou end) LZY22, 
这个结果得到了'2022-02-28'一天的数据
sum(case when D.RQ BETWEEN '2022-01-01'  and (case when((case when year(D.RQ) =2022 and month(D.RQ) = 2 then D.DYM end)) is null then null else '2022-02-28' end )then d.ryou end ) LZY2 ,

上个题我已经给过你提示了

下面是这个sql就是按照我上个题里的思路写的应该符合你的要求

select * from (
select t.jh,mth,sum(ryou_sum) over(partition by jh order by mth) ryou_sum1 from 
(select jh,month(rq) mth,sum(ryou) ryou_sum from CSJING_SCSJB
where rq >='2022-01-01' and rq<='2022-12-31' group by month(rq),jh) t) tt
pivot (max(ryou_sum1) for mth in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as x

sqlserver里实测效果

img

不知道你要不要按jh分组,如果不分组,把jh相关的去掉就行了


没想到是这么老的版本,用下面这个吧


select jh,
case when sum(case when D.RQ BETWEEN '2022-01-01' and '2022-01-31' then d.ryou end) is null then null
else sum(case when D.RQ BETWEEN '2022-01-01' and '2022-01-31' then d.ryou end) end  m1,
case when sum(case when D.RQ BETWEEN '2022-02-01' and '2022-02-28' then d.ryou end) is null then null
else sum(case when D.RQ BETWEEN '2022-01-01' and '2022-02-28' then d.ryou end) end  m2,
case when sum(case when D.RQ BETWEEN '2022-03-01' and '2022-03-31' then d.ryou end) is null then null
else sum(case when D.RQ BETWEEN '2022-01-01' and '2022-03-31' then d.ryou end) end  m3,
case when sum(case when D.RQ BETWEEN '2022-04-01' and '2022-04-30' then d.ryou end) is null then null
else sum(case when D.RQ BETWEEN '2022-01-01' and '2022-04-30' then d.ryou end) end  m4
from CSJING_SCSJB d group by jh

img


sum(case when D.RQ BETWEEN '2022-01-01'  and (case when((case when year(D.RQ) =2022 and month(D.RQ) = 2 then D.DYM end)) then '2022-02-28' else null )then d.ryou end ) LZY2 ,

sum(case when D.DYM is not null and D.RQ BETWEEN '2022-01-01' and '2022-02-28' then d.ryou end) LZY22

主要是没太弄清楚楼主想要的结果, 不知道我猜的对不对
意思就是 如果 DYM 不为空 而且 RQ 在日期内 则求和