简体   繁体   中英

SQL Transpose row to columns

I am trying to transpose rows to columns but I didn't find any good answers.

Here is an example of what I want:

Input tables:


TABLE A    
ID | NAME     
1   | BOB    
2   | JIM    
3   | ROB

TABLE B

ID  | CLUB
1   | 2    
1   | 3    
1   | 4    
2   | 2    
2   | 1    
3   | 5

OUTPUT will be:

ID  | CLUB1 | CLUB2 | CLUB3    
1   | 2     | 3     | 4    
2   | 2     | 1     |    
3   | 5     |       |

You need to enumerate the values to pivot them:

select id,
       max(case when seqnum = 1 then club end) as club_1,
       max(case when seqnum = 2 then club end) as club_2,
       max(case when seqnum = 3 then club end) as club_3
from (select b.*,
             row_number() over (partition by id order by club) as seqnum
      from b
     ) b
group by id;

use conditional aggregation

select id, 
       max(case when id=1 then club end) club1,
       max(case when id=2 then club end) club2,
       max(case when id=3 then club end) club3
from tablename
group by id

use case when

    select a.id,max(case when name='BOB' then CLUB end) ,
    max(case when name='JIM' then CLUB end),
    max(case when name='ROB' then CLUB end)
    tablea a join tableb b on a.id=b.id group by a.id

Sample Data

IF OBJECT_ID('tempdb..#TempTab')IS NOT NULL
DROP TABLE #TempTab
;WITH CTE (ID,CLUB)
AS
(
SELECT 1   , 2 UNION ALL   
SELECT 1   , 3 UNION ALL   
SELECT 1   , 4 UNION ALL   
SELECT 2   , 2 UNION ALL   
SELECT 2   , 1 UNION ALL    
SELECT 3   , 5
)

SELECT  ID,
        CLUB,
        'CLUB'+CAST(ROW_NUMBER()OVER(PARTITION BY ID ORDER BY ID) AS VARCHAR) AS CLUBData
INTO #TempTab
FROM CTE

Dynamic sql

DECLARE @Column nvarchar(1000),@Column2 nvarchar(max),
        @Sql nvarchar(max)

SELECT @Column =STUFF((SELECT DISTINCT  ', '+QUOTENAME(CLUBData)
            FROM #TempTab FOR XML PATH ('')),1,1,'')

SET @Sql = 'SELECT Id,'+@Column +' 
            FROM 
               (
                SELECT * FROM #TempTab 
               ) AS SRc
             PIVOT
               (
                MAX(CLUB) FOR CLUBData IN ('+@Column+')
               ) AS pvt
               '
PRINT @Sql
EXEC (@Sql)

Result

Id  CLUB1   CLUB2   CLUB3
-------------------------
1    3        4       2
2    1        2      NULL
3    5        NULL   NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM