How to pivot without knowing fixed columns in T-SQL

前端 未结 3 1851
失恋的感觉
失恋的感觉 2020-12-20 01:04

I have a table called balance which I wish to pivot, however it is quite difficult since the column names would be labelled 1,2,3 and balances would be sorted b

3条回答
  •  轮回少年
    2020-12-20 01:20

    You can try this way

    select *,concat('Price',RANK() OVER (PARTITION BY i.REFERENCE_NO ORDER BY i.TASK_ID 
     DESC)) AS Rank  into #temp from [dbo].[Table_1] i
    
     select REFERENCE_NO,Price1,Price2,Price3 from 
       (
        select REFERENCE_NO,TASK_ID,Rank from #temp
        ) as cte 
        PIVOT (SUM(TASK_ID)
        FOR rank IN (Price1,Price2,Price3 ))
        as PVT
    

提交回复
热议问题