T-SQL-如何获得此结果集

时间:2019-03-04 14:49:05

标签: sql sql-server tsql

如何获得以下结果集...

PersionId

如果源表看起来像这样...

Desc0, Desc1,      ,Desc2                ,Desc3             , Desc4
ASSETS,Fixed Assets,Tangible Fixed Assets,Land and Buildings, Equipment
ASSETS,Fixed Assets,Tangible Fixed Assets,Vehicles          , Null

我尝试过了...

Desc, type

ASSETS, 0
Fixed Assets,   1
Tangible Fixed Assets,  2
Land and Buildings, 3
Operating Equipment 4, 
Vehicles,   3

1 个答案:

答案 0 :(得分:0)

您想要row_number()并进行条件聚合:

select max(case when [type] = 0 then [desc] end),
       max(case when [type] = 1 then [desc] end),
       max(case when [type] = 2 then [desc] end),
       max(case when [type] = 3 then [desc] end)
from (select a.*,
             row_number() over (partition by [type] order by [desc]) as seq
      from [dbo].[Account] a
     ) a
group by seq;