SQL Server结果集布局

时间:2019-03-08 18:48:24

标签: sql sql-server

SQL新手-我已经提取了将其分配给的人员ID和委员会的列表。每个人被分配到1-4个委员会之间。我想对结果进行布局,以便在每个人的一行中而不是不同的行中填充多个列。

我有这个:

+----+-------------+
| ID | Committee   |
+----+-------------+
|  1 | Awards      |
|  1 | Social Media|
|  1 | Journal     |
|  2 | Social Media|
|  3 | Awards      |
|  3 | Social Media|
|  3 | Journal     |
|  3 | Education   |
|  4 | Journal     |
|  4 | Education   |
|  5 | Awards      |
|  5 | Journal     |
|  5 | Diversity   |
+----+-------------+

而要这样:

+----+--------------+--------------+--------------+--------------+
| ID | Committee1   | Committee2   | Committee3   | Committee4   |
+----+--------------+--------------+--------------+--------------+
|  1 | Awards       | Social Media | Journal      |              |
|  2 | Social Media |              |              |              |
|  3 | Awards       | Social Media | Journal      | Education    |
|  4 | Journal      | Education    |              |              |
|  5 | Awards       | Journal      | Diversity    |              |
+----+--------------+--------------+--------------+--------------+

我的查询是:

选择   ID,   委员会 从   dbo.Membership 哪里   STATUS =“有效”

这似乎很简单,但是我对我所知道的简单SQL命令并不满意,甚至不知道该怎么称呼这种操作。

任何帮助将不胜感激-谢谢!

万一有人偶然发现了这个问题并想要一个答案,这是我要为我工作的代码。 (如果有人看到了改进,我总是渴望学习。):

WITH Memberships AS
(
  SELECT DISTINCT
    ID,
    Committee

    ,RANK() OVER
    (PARTITION BY ID ORDER BY Committee) As MembershipNumber
  FROM
    dbo.Membership
  WHERE
    Status = 'Active'
)

PIVOT(MIN(Committee) FOR MembershipNumber IN ([1],[2],[3],[4])) AS Memberships

ORDER BY ID

0 个答案:

没有答案