简体   繁体   English

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

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

I am working with SQL Server 2008. I have a temp table which returns the this result: 我正在使用SQL Server2008。我有一个临时表,它返回以下结果:

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

I want to get the date of hire of a company and all the information in the same row, and I want the result to be in a format like this: 我想获得公司的聘用日期和所有信息都在同一行中,并且我希望结果采用以下格式:

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

The possible dates of hire can be 4 (201512,201511,201510,201509), but a company cannot have a contract in one of those dates? 可能的聘用日期可以是4(201512,201511,201510,201509),但是公司不能在其中一个日期签约吗?

How to query to get the above result using SQL Server 2008? 如何使用SQL Server 2008查询以获得以上结果?

I tried using a PIVOT in SQL Server 2008 but I failed. 我尝试在SQL Server 2008中使用PIVOT ,但失败了。

I suspect the PIVOT operator is what I need (according to this post, anyway), but I can't figure out how to get started, especially when the number of question_id rows in the table can vary. 我怀疑PIVOT运算符是我需要的(无论如何,根据这篇文章),但是我不知道如何开始,尤其是当表中question_id行的数量可以变化时。 In the above example, it's 5, but in another query the table might be populated with 7 distinct questions. 在上面的示例中,值为5,但在另一个查询中,表中可能填充了7个不同的问题。

You can use pivot or conditional aggregation. 您可以使用pivot或条件聚合。 The key is to get a column for the pivoting -- using row_number() : 关键是要获取用于枢转的列-使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM