sql动态多行转列,PIVOT怎么能转两列?

1.第一条语句使用的case when第二条语句使用PIVOT,怎么能再增加一列《办结数量》2.年月是字段值,怎么能写成动态的select 事项名称,sum(case when 年月 = '2019-01' then 受理数量 else 0 end) as '2019-01受理',sum(case when 年月 = '2019-01' then 办结数量 else 0 end) as '2019-01办结',sum(case when 年月 = '2019-02' then 受理数量 else 0 end) as '2019-02受理',sum(case when 年月 = '2019-02' then 办结数量 else 0 end) as '2019-02办结',sum(case when 年月 = '2019-03' then 受理数量 else 0 end) as '2019-03受理',sum(case when 年月 = '2019-03' then 办结数量 else 0 end) as '2019-03办结',sum(case when 年月 = '2019-04' then 受理数量 else 0 end) as '2019-04受理',sum(case when 年月 = '2019-04' then 办结数量 else 0 end) as '2019-04办结'from newtablegroup by 事项名称select 事项名称,isnull([2019-01],0) as '2019-01受理',isnull([2019-02],0) as '2019-02受理',isnull([2019-03],0) as '2019-03受理',isnull([2019-04],0) as '2019-04受理',isnull([2019-01],0)+isnull([2019-02],0)+isnull([2019-03],0)+isnull([2019-04],0) as '合计'from (select 事项名称,受理数量,年月 from newtable) as APIVOT (sum(受理数量)for 年月 IN ( [2019-01],[2019-02],[2019-03],[2019-04])) AS P
最新回答
纞嗳の方程鉽

2022-02-21 09:39:30

动态最好用存储过程(年月不确定,列名不确定),对sql进行拼接迅薯坦,再写一个第二条语句关于办结的,然后把这个受理与办结通过事项进行关亩桐联查询得手侍到两列结果就好
逗逼太愉快

2021-05-02 18:06:35

你好!
你这个是SQLSERVER?
应该本身念李就不支持仔歼迟PIVOT 的吧!
请您仔细检查一下相应数据库支持的改宴写法吧!
祝你好运!
白发悲花落

2023-10-21 16:57:34

楼上那个用过sqlserver吗?裤判橘

PIVOT是支持的!!!!!

不过看你的语法,肯定报冲帆错。PIVOT最好基于SELECT * 并且先把全部需求的字段转换未列:

select * from

(select CONVERT(varchar(100),年月)+'受理' 栏位,sum(受理数量) 数量 from

 表a

GROUP BY
年月

UNION  ALL

select CONVERT(varchar(100),年月)+'办结'栏位,sum(办结数量) 数量 from

表a

GROUP BY 年月)v

PIVOT ( MAX(v.数量) FOR v.栏位 IN ( [2019-01受理胡团],

[2019-02受理],

[2019-03受理],

[2019-04受理],

[2019-01办结],

[2019-02办结],

[2019-03办结],

[2019-04办结] )) 百度知道回答用