在 SQL Server 2008 中按一列对同一行中的多个结果行进行分组

Group multiple result rows in the same row by one column in SQL Server 2008

我正在使用 SQL Server 2008。我有一个临时 table returns 这个结果:

ID      NAME        TYPE        REGION  DATE_HIRED
--------------------------------------------------
75038   GRUPO FOO   COMPANY A   EUROPE    201512
75038   GRUPO FOO   COMPANY A   EUROPE    201511
75038   GRUPO FOO   COMPANY A   EUROPE    201510

我想获取一家公司的聘用日期和同一行中的所有信息,我希望结果的格式如下:

 ID       NAME       TYPE       REGION   DATE_HIRED1  DATE_HIRED2 DATE_HIRED3...
75038   GRUPO FOO   COMPANY A   EUROPE    201512         201511      201510...

可能的雇佣日期可以是 4 个(201512、201511、201510、201509),但公司不能在其中一个日期签订合同?

如何使用SQL Server 2008查询得到上述结果?

我尝试在 SQL Server 2008 中使用 PIVOT,但失败了。

我怀疑 PIVOT 运算符是我需要的(根据这个 post,无论如何),但我不知道如何开始,尤其是当 [= table 中的 27=] 行可能会有所不同。在上面的示例中,它是 5,但在另一个查询中,table 可能填充了 7 个不同的问题。

您可以使用 pivot 或条件聚合。关键是要获得一个用于旋转的列——使用 row_number():

select id, name, type, region,
       max(seqnum = 1 then date_hired end) as date_hired1,
       max(seqnum = 2 then date_hired end) as date_hired2,
       max(seqnum = 3 then date_hired end) as date_hired3,
       max(seqnum = 4 then date_hired end) as date_hired4
from (select t.*,
             row_number() over (partition by id order by date_hired) as seqnum
      from t
     ) t
group by id, name, type, region;