我有下表
家族
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完成吗?
答案 0 :(得分:0)
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) |