sql server按月份,按项目号展开表格

原始数据:

01 RD21 6495.4114
02 RD21 87.436
04 RD21 101.7184
05 RD21 1.5384
01 RD25 7803.3037
09 RD25 106.8375
01 RD33 20036.4738
02 RD33 2179.80
03 RD33 159.6858
05 RD33 83.8036
06 RD33 82.59
07 RD33 290.24
08 RD33 560.1575
09 RD33 0.00

select c.*,a.amountmoney from (
select rdno,
max(case mondate when '01' then amount else 0 end) as "01",
max(case mondate when '02' then amount else 0 end) as "02",
max(case mondate when '03' then amount else 0 end) as "03",
max(case mondate when '04' then amount else 0 end) as "04",
max(case mondate when '05' then amount else 0 end) as "05",
max(case mondate when '06' then amount else 0 end) as "06",
max(case mondate when '07' then amount else 0 end) as "07",
max(case mondate when '08' then amount else 0 end) as "08",
max(case mondate when '09' then amount else 0 end) as "09",
max(case mondate when '10' then amount else 0 end) as "10",
max(case mondate when '11' then amount else 0 end) as "11",
max(case mondate when '12' then amount else 0 end) as "12"
from ( select datename(mm,operdate) as mondate,rdno,sum(summoney) as amount
from fp_pr_materialdetail with(nolock)
where operdate<='2018-12-31' and operdate>='2018-01-01'
group by datename(mm,operdate),rdno
) b group by rdno) c
left join (select rdno,sum(amount) as amountmoney from (
select rdno,sum(summoney) as amount
from fp_pr_materialdetail with(nolock)
where operdate<='2018-12-31' and operdate>='2018-01-01'
group by rdno
) k group by rdno) a on a.rdno=c.rdno

结果数据:

RDno 01       02       03     04       05       06    07     08     09     10  11   12

RD21 6495.4114 87.436 0.00 101.7184 1.5384 0.00 0.00 0.00 0.00 0.00 0.00 0.00 6686.1042
RD25 7803.3037 0.00 0.00 0.00 0.00 0.00 0.00 0.00 106.8375 0.00 0.00 0.00 7910.1412
RD33 20036.4738 2179.80 159.6858 0.00 83.8036 82.59 290.24 560.1575 0.00 0.00 0.00 0.00 23392.7507

原文地址:https://www.cnblogs.com/yc-shen/p/9963036.html