带连接的表上的SQL server pivot

时间:2016-02-03 17:32:16

标签: sql-server tsql

我有这个简单的sql语句:

SELECT FCDT.description AS DetailType, FCD.data
FROM Contact_Detail FCD
LEFT JOIN Contact_Detail_Types FCDT
ON FCD.contact_detail_types_id=FCDT.contact_detail_types_id
WHERE contacts_id='4AA36958--0804CA'

产生了这个结果:

DetailType   data
-------------------------------
Phone        123-456-7890
Email        myEmail@domain.com

我需要将此行转换为列,以获得此结果:

Phone         Email
--------------------------------
123-456-7890  myEmail@domain.com

我怎么能做到这一点?我有几个小时玩转轴功能,但到目前为止没有结果。

1 个答案:

答案 0 :(得分:1)

Select * From
(SELECT FCDT.description AS DetailType, FCD.data As Data
FROM Contact_Detail FCD
LEFT JOIN Contact_Detail_Types FCDT
ON FCD.contact_detail_types_id=FCDT.contact_detail_types_id
WHERE contacts_id='4AA36958--0804CA')P
pivot
(Max(Data) for DetailType in ([Phone], [Email])) As Pvt