如何将SQL JOIN的结果显示为单独的列?

时间:2015-06-24 20:37:35

标签: sql-server sql-server-2008-r2 group-by pivot

我正在尝试连接两个表,然后将结果解析为单独的列,如下所示:

表1:

Customer_ID
----------
1
2
3

表2:

Customer_ID ListID
------------------
1           1
1           2
1           5
2           1
2           3

期望的结果:

Customer_ID ListID1 ListID2 ListID3
-----------------------------------
1           1       2       5
2           1       3   
3   

我使用LEFT JOIN将表和GROUP BY组合在一起,使用相同的Custmer_ID对列进行分组,如下所示:

SELECT MIN([Table1].[Customer_ID])
    ,MIN([Table2].[ListID])
FROM [Table1]
LEFT JOIN [Table2]
ON [Table2].[Customer_ID] = [Table1].[Customer_ID]
GROUP BY [Table1].[Customer_ID]

当前结果:

Customer_ID ListID
------------------
1           1
2           1
3           NULL

我无法弄清楚从哪里开始将ListID解析为单独的列。有没有办法迭代ListID的?

1 个答案:

答案 0 :(得分:1)

这是唯一的,因为您要透视的列不存在。您可以使用Row_number窗口功能创建它。它看起来像这样:

SELECT Customer_ID, [1] ListID1, [2] ListID2, [3] ListID3
FROM
(select Table1.Customer_ID, 
    Table2.ListID,
    ROW_NUMBER() over (Partition by Table1.Customer_ID Order By Table2.ListID) RowNum
from Table1
LEFT JOIN Table2
ON Table2.[Customer_ID] = Table1.[Customer_ID]) as SourceTable
PIVOT
(
max(ListID)
FOR RowNum IN ([1], [2], [3])
) AS PivotTable

这只会显示列中前三个ListID值。如果您需要更多值,可以添加更多RowNum值。