首页 > 解决方案 > Sql如何在不丢失数据的情况下对列进行分组

问题描述

我正在使用 SQL Server 2014,我想在不丢失数据的情况下对我的行进行分组。

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

在此处输入图像描述

我想要实现的是:

在此处输入图像描述

标签: sqlsql-servergroup-byrow

解决方案


这很棘手。基本上,这个想法是一个不可旋转和重新旋转,但有一个转折:

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;

推荐阅读