SQL将行转列

时间:2019-03-13 10:42:39

标签: sql sql-server tsql pivot

我正在尝试将行转置为列,但是找不到任何好的答案。

这是我想要的例子:

输入表:


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

输出将是:

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

4 个答案:

答案 0 :(得分:0)

您需要枚举值以对其进行透视:

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;

答案 1 :(得分:0)

使用条件聚合

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

答案 2 :(得分:0)

用例何时

    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

答案 3 :(得分:0)

样本数据

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

动态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)

结果

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