![](/img/trans.png)
[英]How to do this sql query for aggregating counts in a one-to-many relationship
[英]Pivot a table with data in a one-to-many relationship without aggregating?
我有看起来像这样的数据:
ID | Type ID | Value
---------------------
1 | 1 | 1
1 | 1 | 2
2 | 1 | 1
2 | 2 | 1
我希望它看起来像这样:
ID | Type ID 1 | Type ID 2
-----------------------------
1 | 1 | NULL
1 | 2 | NULL
2 | 1 | 2
我曾尝试摆弄PIVOT运算符,但这似乎需要一个我不想要的聚合函数。
此外,使用子选择手动执行它不是一种选择,因为 ID 非常多并且是动态的。 有任何想法吗?
我想你想要条件聚合。 . . 但是有枚举:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.