简体   繁体   中英

Pivot a table with data in a one-to-many relationship without aggregating?

I have data that looks like this:

ID  | Type ID | Value
---------------------
1   |    1    |   1
1   |    1    |   2
2   |    1    |   1
2   |    2    |   1

And I would like it to look like this:

ID  | Type ID 1  |  Type ID 2
----------------------------- 
1   |     1      |    NULL
1   |     2      |    NULL
2   |     1      |    2

I have tried fiddling with the PIVOT operator, but this seems to require an aggregate function, which I don't want.

Also, doing it manually with sub-selects isn't an option because the IDs are quite numerous and dynamic. Any ideas?

I think you want conditional aggregation . . . but with enumeration thrown in:

select id,
       max(case when type_id = 1 then value end) as value_1,
       max(case when type_id = 2 then value end) as value_2
from (select t.*,
             row_number() over (partition by id, type_id order by id) as seqnum
      from t
     ) t
group by id, seqnum

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