现在有这样一张表,如下:
CREATE TABLE tbl_列转行测试(
[UserID] [int] NULL,
[UserNo] [int] NULL,
企业养老 int,
企业医疗 int,
企业工伤 int,
企业养老补缴 int,
企业养老补缴月 int,
企业医疗补缴 int,
企业医疗补缴月 int,
企业工伤补缴 int,
企业工伤补缴月 int,
个人养老 int,
个人医疗 int,
个人养老补缴 int,
个人养老补缴月 int,
个人医疗补缴 int,
个人医疗补缴月 int,
Num int
) ON [PRIMARY]
insert into tbl_列转行测试 values(1,1,11,22,33,55,2,32,3,54,5,56,67,10,3,12,6,12345567)
原表运行结果如下:
现在需要把这一行数据,转化为如下的结果:
该如何实现呢???
尝试用case when than
能否给个例子呢
这个问题现在有了这样的解决方法了,第一部,先把企业部分的列转行,代码和效果如下:
select * into #tempAA from (
SELECT USERID,USERNO,险种类型=attribute,value as 企业金额,
CASE attribute
when '企业养老' then (select 企业养老补缴 from tbl_列转行测试 b where UserID=UPV.Userid)
when '企业医疗' then (select 企业医疗补缴 from tbl_列转行测试 b where UserID=UPV.Userid)
when '企业工伤' then (select 企业工伤补缴 from tbl_列转行测试 b where UserID=UPV.Userid)
else 0 end as 企业补缴金额,
CASE attribute
when '企业养老' then (select 企业养老补缴月 from tbl_列转行测试 b where UserID=UPV.Userid)
when '企业医疗' then (select 企业医疗补缴月 from tbl_列转行测试 b where UserID=UPV.Userid)
when '企业工伤' then (select 企业工伤补缴月 from tbl_列转行测试 b where UserID=UPV.Userid)
else 0 end as 企业补缴月份,
Num
FROM (select * from tbl_列转行测试)a
UNPIVOT
(
value FOR attribute IN(企业养老,企业医疗,企业工伤)
) AS UPV
) AA
再把个人部分的列转行,代码和效果如下:
select * into #tempBB from (
SELECT USERID,USERNO,险种类型=attribute,value as 个人金额,
CASE attribute
when '个人养老' then (select 个人养老补缴 from tbl_列转行测试 b where UserID=UPV.Userid)
when '个人医疗' then (select 个人医疗补缴 from tbl_列转行测试 b where UserID=UPV.Userid)
else 0 end as 个人补缴金额,
CASE attribute
when '个人养老' then (select 个人养老补缴月 from tbl_列转行测试 b where UserID=UPV.Userid)
when '个人医疗' then (select 个人医疗补缴月 from tbl_列转行测试 b where UserID=UPV.Userid)
else 0 end as 个人补缴月份,
Num
FROM (select * from tbl_列转行测试)a
UNPIVOT
(
value FOR attribute IN(个人养老,个人医疗)
) AS UPV
) BB
然后再把这两个临时表合并,代码和效果如下:
select a.userid,a.userno,right(a.险种类型,2) as 险种类型,a.企业金额,b.个人金额,a.企业补缴金额 as 企业补缴,b.个人补缴金额 as 个人补缴,a.企业补缴月份,b.个人补缴月份,a.num
from #tempAA a
left join #tempBB b on a.userid=b.userid and right(a.险种类型,2)=right(b.险种类型,2)
where a.UserID=1
至此,本问题完美解决!!