TSQL从行转换为列无聚合

时间:2014-12-16 02:40:23

标签: sql sql-server tsql transformation

我从已导入的csv文件中获得以下样式数据

Appt_ID,Sched_ID,Person_ID,Order_Field_Name,Order_Field Value
10001,2002,123456,Name,Fred Jones
10001,2002,123456,Address,"123 ABC St, Seasame Town"
10001,2002,123456,Appt_type,Consultation
10001,2002,123456,Sched_Start_time,12:00PM
10001,2002,123456,Sched_End_time,02:00PM
10001,2002,123456,Appt_With,Larry Smithe,
10002,2000,987654,Name,Mary Mags
10002,2000,987654,Address,"258 Street Ave, Neverland"
10002,2000,987654,Appt_type,Procedure
10002,2000,987654,Sched_Start_time,10:00AM
10002,2000,987654,Sched_End_time,4:00PM
10002,2000,987654,Appt_With,Larry Smithe

我需要将其转换为这样。我尝试使用枢轴功能,但没有正确出现。

Appt_ID,Sched_ID,Person_ID,Name,Address,Appt_type,Sched_Start_time,Sched_End_time,Appt_With
10001,2002,123456,Fred Jones,"123 ABC St, Seasame Town",Consultation,12:00PM,02:00PM,Larry Smithe
10002,2000,987654,Mary Mags,"258 Street Ave, Neverland",Procedure,10:00AM,4:00PM,Larry Smithe

任何帮助都会很棒。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

select appt_id, sched_id, person_id,
       max(case when order_field = 'Name' then order_value end) as name,
       max(case when order_field = 'Address' then order_value end) as address,
       max(case when order_field = 'Appt_type' then order_value end) as appt_type,
       . . .
from table t
group by appt_id, sched_id, person_id;