Convert Rows to columns using 'Pivot' in mssql when columns are string data type

前端 未结 3 1699
情深已故
情深已故 2020-12-16 04:10

I need to know whether \'pivot\' in MS SQL can be used for converting rows to columns if there is no aggregate function to be used. i saw lot of examples with aggregate func

3条回答
  •  时光说笑
    2020-12-16 04:18

    You can use a PIVOT to perform this operation. When doing the PIVOT you can do it one of two ways, with a Static Pivot that you will code the rows to transform or a Dynamic Pivot which will create the list of columns at run-time:

    Static Pivot (see SQL Fiddle with a Demo):

    SELECT *
    FROM
    (
      select empid, wagecode, amount
      from t1
    ) x
    pivot
    (
      sum(amount)
      for wagecode in ([basic], [TA], [DA])
    ) p
    

    Dynamic Pivot:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);
    
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(wagecode) 
                      FROM t1 
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT empid, ' + @cols + ' from 
                 (
                     select empid, wagecode, amount
                     from t1
                ) x
                pivot 
                (
                    sum(amount)
                    for wagecode in (' + @cols + ')
                ) p '
    
    execute(@query)
    

    Both of these will give you the same results

提交回复
热议问题