如何使用 1 列中的数据创建 2 列并将它们合并
How to create 2 columns using data from 1 column and merging them
我在大查询中遇到了一些问题,单列无法分成两列。我希望带有 8 和 10 的列索引是名为 universal_id 和 project_id 的新列,使用列“value”中的值。
我目前的table是:
user_id | index | value
a. | 1. | 123
b. | 8. | 456
c. | 10. | 12.60
b. | 10. | 789
我希望结果是这样的:
user_id | project_id | universal_id |
a | NA | NA
b. | 789 | 456
c. | 12.60 | NA
我已经试过了,但是没有用。我搜索了很多地方,都能找到我要找的答案。任何帮助将不胜感激。提前致谢!!!
select user_id,
case when index = 8 then value else null end as universal_id,
case when index = 10 then value else null end as ps_project_id
from test_1
您可以在此处使用条件聚合:
SELECT
user_id,
MAX(CASE WHEN index = 10 THEN value END) AS project_id,
MAX(CASE WHEN index = 8 THEN value END) AS universal_id
FROM test_1
GROUP BY user_id;
考虑以下方法
select * from your_table
pivot (
min(value) for case index
when 10 then 'project_id'
when 8 then 'universal_id'
end in ('project_id', 'universal_id')
)
如果应用于您问题中的示例数据 - 输出为
我在大查询中遇到了一些问题,单列无法分成两列。我希望带有 8 和 10 的列索引是名为 universal_id 和 project_id 的新列,使用列“value”中的值。
我目前的table是:
user_id | index | value
a. | 1. | 123
b. | 8. | 456
c. | 10. | 12.60
b. | 10. | 789
我希望结果是这样的:
user_id | project_id | universal_id |
a | NA | NA
b. | 789 | 456
c. | 12.60 | NA
我已经试过了,但是没有用。我搜索了很多地方,都能找到我要找的答案。任何帮助将不胜感激。提前致谢!!!
select user_id,
case when index = 8 then value else null end as universal_id,
case when index = 10 then value else null end as ps_project_id
from test_1
您可以在此处使用条件聚合:
SELECT
user_id,
MAX(CASE WHEN index = 10 THEN value END) AS project_id,
MAX(CASE WHEN index = 8 THEN value END) AS universal_id
FROM test_1
GROUP BY user_id;
考虑以下方法
select * from your_table
pivot (
min(value) for case index
when 10 then 'project_id'
when 8 then 'universal_id'
end in ('project_id', 'universal_id')
)
如果应用于您问题中的示例数据 - 输出为