SQL Server将行转换为列动态列

时间:2014-08-16 18:59:10

标签: sql-server pivot

我有下表

家族

id     name
-------------
1      Joe

1      Jim

1      Jane

2      Matt

2      Pat

3      Gary

3 Mike

想要

id     name1,   name2,   name3, name4 ....

1      Joe      Jim      Jane

2      Matt     Pat

3      Gary     Mike.

可以使用PIVOT完成吗?

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Test_TABLE(id INT, name VARCHAR(10))
GO

INSERT INTO Test_TABLE VALUES 
(1 ,'Joe'),(1 ,'Jim'),(1 ,'Jane'),
(2 ,'Matt'),(2 ,'Pat'),(3 ,'Gary')
GO

查询1

SELECT * FROM 
(
    SELECT *
           ,'Name' + CAST(ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID ASC) AS VARCHAR(3)) Names
    FROM Test_TABLE )t
PIVOT (MAX(Name)
       FOR Names
       IN (Name1,Name2,Name3)
      )p

<强> Results

| ID | NAME1 |  NAME2 |  NAME3 |
|----|-------|--------|--------|
|  1 |   Joe |    Jim |   Jane |
|  2 |  Matt |    Pat | (null) |
|  3 |  Gary | (null) | (null) |