简体   繁体   中英

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:

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?

How to query to get the above result using SQL Server 2008?

I tried using a PIVOT in SQL Server 2008 but I failed.

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. In the above example, it's 5, but in another query the table might be populated with 7 distinct questions.

You can use pivot or conditional aggregation. The key is to get a column for the pivoting -- using 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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