22,210
社区成员
发帖
与我相关
我的任务
分享
create table JLLS(YHID int,RQ datetime,jymid int,fsje int,bmid int)
create table JLLSTMP(YHID int,RQ datetime,jymid int,fsje int,bmid int)
insert into JLLS
select 1, '2019-06-17 08:01:01', 30, -10, 3 union all
select 1, '2019-06-17 08:01:01', 31, 11, 3 union all
select 1, '2019-06-17 08:01:01', 38, 100, 3 union all
select 1, '2019-06-15 08:01:01', 38, 30, 3 union all
select 1, '2019-06-17 08:01:01', 40, 150, 3 union all
select 1, '2019-06-12 08:01:01', 38, 50, 3
insert into JLLSTMP
select 1, '2019-06-17 08:01:01', 30, -10, 4 union all
select 1, '2019-06-17 08:01:01', 31, -3, 4 union all
select 1, '2019-06-17 08:01:01', 38, 100, 4 union all
select 1, '2019-06-17 08:01:01', 40, 150, 4
with u as(
select YHID,bmid,jymid,fsje=sum(fsje),bs=count(1)
from
(select YHID,RQ,jymid,fsje,bmid
from JLLS
union all
select YHID,RQ,jymid,fsje,bmid
from JLLSTMP) t
where YHID=1 and jymid in(30,31,38,40)
group by YHID,bmid,jymid),
v as(
select YHID,bmid,val,
col=col+case jymid when 38 then '1' when 40 then '2' when 30 then '3' when 31 then '4' else '' end
from u
unpivot(val for col in(fsje,bs)) p)
select a.YHID,a.[fsje1],a.[bs1],a.[fsje2],a.[bs2],a.[fsje3],a.[bs3],a.[fsje4],a.[bs4],
b.Zje,b.Zbs,a.bmid
from (select YHID,bmid,[fsje1],[bs1],[fsje2],[bs2],[fsje3],[bs3],[fsje4],[bs4]
from v
pivot(max(val) for col in([fsje1],[bs1],[fsje2],[bs2],[fsje3],[bs3],[fsje4],[bs4])) p) a
inner join (select YHID,bmid,
Zje=sum(case when col like 'fsje%' then val else 0 end),
Zbs=sum(case when col like 'bs%' then val else 0 end)
from v
group by YHID,bmid) b on a.YHID=b.YHID and a.bmid=b.bmid
/*
YHID fsje1 bs1 fsje2 bs2 fsje3 bs3 fsje4 bs4 Zje Zbs bmid
----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
1 180 3 150 1 -10 1 11 1 331 6 3
1 100 1 150 1 -10 1 -3 1 237 4 4
(2 行受影响)
*/