在SQL Server中如何将列数据更改为行格式?

时间:2015-06-15 13:21:24

标签: sql sql-server

在SQL Server中如何将列数据更改为行格式?...

例如:

输入

Name   date
--------------
xxx    12/12/2015
xxx    11/12/2015
xxx    10/12/2015
yyy    9/12/2015

期望的输出:

Name  Date
------------------------------------------
xxx   10/12/2015  11/12/2015  12/12/2015
yyy   9/12/2015

1 个答案:

答案 0 :(得分:0)

检查一下:

DECLARE @DataSource TABLE
(
    [name] CHAR(3)
   ,[date] DATE
);

INSERT INTO @DataSource ([name], [date])
VALUES ('xxx', '12/12/2015')
      ,('xxx', '11/12/2015')
      ,('xxx', '10/12/2015')
      ,('yyy', '9/12/2015');

WITH DataSource AS
(
    SELECT DISTINCT [name]
    FROM @DataSource
)
SELECT [name]
      ,STUFF
       (
            (
                SELECT ' ' + CAST([date] AS VARCHAR(12)) 
                FROM @DataSource
                WHERE DS.[name] = [name]
                ORDER BY [date] ASC
                FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)')
            ,1
            ,1
            ,''
        )
FROM DataSource DS;

enter image description here