SQL如何对列进行分组而不丢失数据

时间:2018-07-13 16:55:05

标签: sql sql-server group-by row

我正在使用SQL Server 2014,并且希望对行进行分组而不丢失数据。

这是我到目前为止所拥有的:

enter image description here

我要实现的是:

enter image description here

1 个答案:

答案 0 :(得分:0)

这很棘手。基本上,这个想法是不可逆转的,但有一个转折点:

select t.id,
       max(case when which = 'codeTaxe1' then val end) as codeTaxe1,
       max(case when which = 'codeTaxe2' then val end) as codeTaxe2,
       . . . 
from t cross apply
     (select v.*, row_number() over (order by (select null)) as seqnum
      from (values (t.codeTaxe1, 'codeTaxe1'), (t.codeTaxe2, 'codeTaxe2'), . . .
           ) v(val, which)
      where val is not null
     ) tt
group by t.id, seqnum;