PIVOT 和 JOIN IN sql

问题描述 投票:0回答:1

希望有人能帮助我。

SELECT id.id, ticket.ticket FROM tabla.id JOIN tabla.ticket ON id.sym = ticket.sym

我得到的结果如下:

| id | ticket | 
| -- | ------ | 
| 1  |   A1   | 
| 1  |   A2   |
| 1  |   A3   |
| 2  |   E1   |
| 2  |   E2   |
| 2  |   E3   | 
| .  |    .   | 
| .  |    .   | 
| n  |    n   | 

结果显示,对于单个 ID,可以有许多不同的票证与同一 ID 关联,我需要的是获得水平的东西,因为该表来自一个联接,并且我将通过其他联接添加更多列。我希望能得到这样的东西..

|    id    | Column B | Col c | Col D | Col N |
|    1     |    A1    |   A2  |  A3   |  A4   | 
|    2     |    B1    |   B2  |  B3   |  NULL | 
|    N     |    N     |  
sql pivot-table
1个回答
0
投票

我建议为每个 id 组添加行编号,然后将每个行号别名为数据透视后的 B、C、D、E... 列

--Create example table
CREATE TABLE [tablaPlusId] 
(
    [id]    VARCHAR(512),
    [ticket]    VARCHAR(512)
);

--insert into example table
INSERT INTO [tablaPlusId] ([id], [ticket]) VALUES
    ('1', 'A1'),
    ('1', 'A2'),
    ('1', 'A3'),
    ('1', 'A4'),  
    ('2', 'E1'),
    ('2', 'E2'),
    ('2', 'E3');

--Add row numbering within each id group
SELECT *, ROW_NUMBER()  OVER(PARTITION BY id ORDER BY id ASC) AS rn  
INTO #temp
FROM tablaPlusId

Print 'Validate the numbering of items within an id group'  
Select * from #temp

Print 'Pivot on Ticket then alias each row number column as B,C,D,...'  
SELECT ID, [1] as [Column B], [2] as [Column C], [3] as [Column D], [4] as [Column E]
FROM  #temp
PIVOT 
(
  MIN(ticket)  
  FOR rn IN ([1], [2], [3], [4])  
) AS PivotTable; 

小提琴

身份证 B 栏 C 栏 D 栏 E 栏
1 A1 A2 A3 A4
2 E1 E2 E3
© www.soinside.com 2019 - 2024. All rights reserved.