英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论