2015-06-24 74 views
3

我試圖連接兩個表,然後分析出的結果爲單獨列像這樣:如何將SQL JOIN的結果顯示爲單獨的列?

表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的?

+0

請看看透視功能http://stackoverflow.com/questions/14797691/dynamic-pivot-columns-in-sql-server – Hituptony

回答

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值。

+0

這工作,謝謝你噓!我肯定會去研究數據透視表。 – user3669766