sql server 2008中的透视sql数据

gpnt7bae  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(396)

我需要在SQLServer2008中透视数据。有人能给我指点一下吗?
我的原始数据如下所示:

create table #tbl (
ServiceDesc_2 varchar(20), ListCode_2 varchar(10), LongestWaitingDays_2 int, AvgWaitingDays_2 int, TotalPatientsWaiting_2 int);

insert #tbl 
    select 'XYZ - Left Side',   'Booked',   67, 16, 38
 union all 
    select  'XYZ - Left Side',  'UnBooked', 23, 6, 53
union all 
    select  'XYZ - Right Side', 'Booked',   14, 8, 2
union all 
    select  'XYZ - Right Side', 'UnBooked', 4, 3, 2

我正在努力实现以下目标:

ifsvaxew

ifsvaxew1#

您可以使用 cross apply 将行相乘以复制列。
然后可以执行条件聚合以获得所需的结果。
下面是一个示例查询:

;with c as
    (
        select ServiceDesc_2,col,val as measures,ListCode_2,ord  
        from #tbl 
        cross apply 
        (
            values 
             ('LongestWaitingDays_2'  ,LongestWaitingDays_2  , 1)
            ,('AvgWaitingDays_2'      ,AvgWaitingDays_2      , 2)
            ,('TotalPatientsWaiting_2',TotalPatientsWaiting_2, 3)
        )
        CS (col,val,ord)
    )
select 
     ServiceDesc_2  
    ,col as Measures
    ,MAX(case when ListCode_2='UnBooked' then measures else null end) as UnBooked
    ,MAX(case when ListCode_2='Booked'   then measures else null end) as Booked
from c
group by ServiceDesc_2, col
order by ServiceDesc_2, max(ord)

输出:

相关问题