SQL查询麻烦

时间:2011-04-22 21:38:15

标签: sql sql-server-2005

我有一个场景需要将行转换为列。我可能需要使用PIVOT,但我无法弄清楚这一点。

以下是我所拥有的简化版本: 表:ContentAuthor

ContentID | AuthorName
----------------------
1         | Joe
1         | John
1         | Mary
2         | John
2         | Dan
3         | Sam

我想得到什么:

ContentID | Author1  | Author2  | Author3  | Author4  | Author5
-----------------------------------------------------------------
1         | Joe      | John     | Mary     |          |
2         | John     | Dan      |          |          |
3         | Sam      |          |          |          |

此时我并不关心他们出现的顺序。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

如果您需要允许任意金额,那么每ContentId最多可以为5位作者工作,那么您需要使用dynamic SQL

;WITH ContentAuthor(ContentID, AuthorName) AS
(
SELECT 1,'Joe' UNION ALL
SELECT 1,'John' UNION ALL
SELECT 1,'Mary' UNION ALL
SELECT 2,'John' UNION ALL
SELECT 2,'Dan' UNION ALL
SELECT 3,'Sam'
),T AS
(
 SELECT *,
        ROW_NUMBER() OVER (PARTITION BY ContentID ORDER BY (SELECT 0)) RN
 FROM ContentAuthor
)
SELECT ContentID,
       [1] AS Author1,
       [2] AS Author2,
       [3] AS Author3,
       [4] AS Author4,
       [5] AS Author5
FROM T
PIVOT(MAX(AuthorName) FOR RN IN ([1],[2],[3],[4],[5])) AS Pvt;