简体   繁体   English

PIVOT SQL 数据在 SQL 服务器 2008

[英]PIVOT SQL data in SQL Server 2008

I need to pivot data in SQL Server 2008. Can someone please give me some pointers to look around?我需要 SQL Server 2008 中的 pivot 数据。有人可以给我一些指点吗?

My Raw data looks like as:我的原始数据如下所示:

在此处输入图像描述

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

I am trying to achieve below:我正在努力实现以下目标:

在此处输入图像描述

You can prepare your data with cross apply to multiply the rows in order to replicate the columns.您可以使用cross apply准备数据以将行相乘以复制列。

Then you can perform a conditional aggregation to obtain the desired results.然后您可以执行条件聚合以获得所需的结果。

Here is a sample query that should work:这是一个应该工作的示例查询:

 ;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)

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM