将多列转置为一行列

时间:2016-10-02 13:37:11

标签: sql-server tsql

我有以下数据:

Tag Name          PRD             Start            End 
10PIC700422.PV  10-PSV-700073A  9/9/16 10:44    9/9/16 10:49
10PIC700422.PV  10-PSV-700073B  9/9/16 10:44    9/9/16 10:49
10PIC700422.PV  10-PSV-700073A  9/9/16 10:50    9/9/16 10:51
10PIC700422.PV  10-PSV-700073B  9/9/16 10:50    9/9/16 10:51
11PIC41010.PV   11-PSV-401002A  4/4/16 12:51    4/4/16 13:58
11PIC41010.PV   11-PSV-401002B  4/4/16 12:51    4/4/16 13:58
11PIC41010.PV   11-PSV-401002A  4/4/16 14:04    4/4/16 14:29
11PIC41010.PV   11-PSV-401002B  4/4/16 14:04    4/4/16 14:29

我希望按标签名称和开始日期时间进行分组,并获得不同的标签名称和开始日期时间,但PRD应转换为单行,标签名称为一列,请参阅结果我想要获取:

Tag Name PRD                                    Start           End 
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:44    9/9/16 10:49
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:50    9/9/16 10:51
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 12:51    4/4/16 13:58
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 14:04    4/4/16 14:29
提前谢谢。 小号

1 个答案:

答案 0 :(得分:0)

试试这个,

declare @t table(Tag_Name varchar(50), PRD varchar(50),Startdt datetime ,Enddt datetime)
insert into @t values
('10PIC700422.PV','10-PSV-700073A','9/9/16 10:44','9/9/16 10:49')
,('10PIC700422.PV','10-PSV-700073B','9/9/16 10:44','9/9/16 10:49')
,('10PIC700422.PV','10-PSV-700073A','9/9/16 10:50','9/9/16 10:51')
,('10PIC700422.PV','10-PSV-700073B','9/9/16 10:50','9/9/16 10:51')
,('11PIC41010.PV','11-PSV-401002A','4/4/16 12:51','4/4/16 13:58')
,('11PIC41010.PV','11-PSV-401002B','4/4/16 12:51','4/4/16 13:58')
,('11PIC41010.PV','11-PSV-401002A','4/4/16 14:04','4/4/16 14:29')
,('11PIC41010.PV','11-PSV-401002B','4/4/16 14:04','4/4/16 14:29')

;

WITH CTE
AS (
    SELECT *
        ,ROW_NUMBER() OVER (
            PARTITION BY tag_name
            ,startdt ORDER BY startdt
            ) rn
    FROM @t
    )
SELECT tag_name
    ,stuff((
            SELECT '-' + prd
            FROM cte c1
            WHERE c.Tag_Name = c1.Tag_Name
                AND c.Startdt = c1.Startdt
            FOR XML path('')
            ), 1, 1, '') PRD
    ,startdt
    ,enddt
FROM cte c
WHERE rn = 1