sybase/sql 自连接多行

sybase/sql self join multiple rows

嗨,Whosebug 社区,

如果列 1 中的唯一 ID 相同,我正在尝试进行自连接。

Table代码:

CREATE TABLE #table (
  Unique_ID int, Product_code varchar(10)
)
INSERT INTO #table (Unique_ID, Product_code) VALUES (1111111111, 1)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (1111111111, 2)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (1111111111, 3)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (2222222222, 4)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (2222222222, 4)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (3333333333, 5)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (3333333333, 6)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (3333333333, 6)      
INSERT INTO #table (Unique_ID, Product_code) VALUES (3333333333, 3)      

#table 输入:

Unique_ID   Product_code
1111111111       1      
1111111111       2      
1111111111       3      
2222222222       4      
2222222222       4      
3333333333       5      
3333333333       6      
3333333333       6      
3333333333       3      

期望#table输出:

Unique_ID   Product_code  Product_code1  Product_code2  Product_code3
1111111111       1              2              3            (Null)      
2222222222       4              4            (Null)         (Null)   
3333333333       5              6              6               3

当前代码(不确定如何通过Unique_ID比较每一行):

SELECT t1.Unique_ID, t1.Product_code, t2.Product_code AS [Product_code1]
FROM #temp AS t1
JOIN #temp AS t2 ON t1.Unique_ID = t2.Unique_ID
ORDER BY t1.Unique_ID  

任何提示and/or帮助将不胜感激谢谢

由于您希望每个结果行有 3 个产品代码,因此您必须进行 3 向自联接。现在你有一个双向自连接,所以你必须用#table再次连接

试试这个。您需要一个中间步骤来通过相同的列关联不同的值:

select *, seq=identity(int) into #temp from #table order by Unique_ID, Product_code
go

SELECT t1.Unique_ID, t1.Product_code as p1, t2.Product_code as p2, t3.Product_code as p3, t4.Product_code as p4
FROM #temp AS t1
LEFT JOIN #temp AS t2 ON t1.Unique_ID = t2.Unique_ID and t2.seq = t1.seq+1
LEFT JOIN #temp AS t3 ON t2.Unique_ID = t3.Unique_ID and t3.seq = t2.seq+1
LEFT JOIN #temp AS t4 ON t1.Unique_ID = t4.Unique_ID and t4.seq = t3.seq+1
where t1.seq = (select min(seq) from #temp where Unique_ID = t1.Unique_ID)
ORDER BY t1.Unique_ID  
go