SQL将值的组合转化为列,记录组合是否存在。

huangapple go评论58阅读模式
英文:

SQL turn combinations of values into columns that log combination's existence or not

问题

给定一个类似以下格式的PSQL表格结果:

ID 颜色
123 红色
123 蓝色
456 绿色
789 红色
789 绿色

我想要以以下的视图返回结果:

ID 红色 绿色 蓝色
123 X X
456 X
789 X X
其中 'X' 代表在原始结果表格中ID和颜色的组合存在。
英文:

Given a PSQL table of results like so:

ID Color
123 Red
123 Blue
456 Green
789 Red
789 Green

I would like to return the results in the following view:

ID Red Green Blue
123 X X
456 X
789 X X

where an 'X' represents that the combination of ID and Color exists in my original results table.

答案1

得分: 1

你可以使用条件聚合。例如:

选择
  id,
  max(case 当颜色 = '红色' 时 then 'X' end) as 红色,
  max(case 当颜色 = '绿色' 时 then 'X' end) as 绿色,
  max(case 当颜色 = '蓝色' 时 then 'X' end) as 蓝色
从 t
按 id 分组
英文:

You can use conditional aggregation. For example:

select
  id,
  max(case when color = 'Red' then 'X' end) as red,
  max(case when color = 'Green' then 'X' end) as green,
  max(case when color = 'Blue' then 'X' end) as blue
from t
group by id

huangapple
  • 本文由 发表于 2023年6月15日 05:12:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定