SQL 如何在一列中获取值并将这些值作为附加列
How to take values in one column and have those values be additional columns instead, in SQL
假设我有一个名为 'Fruit' 的列,它具有以下三个值:
ID | Fruit |
010 | Apple |
020 | Orange |
010 | Pear |
假设还有其他列,例如 Profile_ID。我如何让 table 改为这样读取,其中一列中的值现在是它们自己的列,并且当配置文件与给定水果相关联时,它将显示 'X' 在该行中:
ID | Apple | Orange | Pear
010 | x | | x
020 | | x |
您可以使用条件聚合。如果您想要一个特定的配置文件 ID,则:
select id,
max(case when fruit = 'Apple' and profile_id = ? then 'X' end) as apple,
max(case when fruit = 'Orange' and profile_id = ? then 'X' end) as orange,
max(case when fruit = 'Pear' and profile_id = ? then 'X' end) as pear
from t
group by id;
如果您只想知道某行是否存在:
select id,
max(case when fruit = 'Apple' then 'X' end) as apple,
max(case when fruit = 'Orange' then 'X' end) as orange,
max(case when fruit = 'Pear' then 'X' end) as pear
from t
group by id;
以下适用于 BigQuery 标准 SQL 并且足够通用以处理任意数量的不同“水果”并且不需要手动输入和明确提及所有这些
EXECUTE IMMEDIATE (
SELECT """
SELECT id, """ ||
STRING_AGG("""MAX(IF(Fruit = '""" || Fruit || """', 'X', '')) AS """ || Fruit, ', ')
|| """
FROM `project.dataset.table`
GROUP BY id
"""
FROM (
SELECT DISTINCT Fruit
FROM `project.dataset.table`
ORDER BY Fruit
)
);
如果应用于您问题中的示例数据 - 输出为
Row id Apple Orange Pear
1 010 X X
2 020 X
假设我有一个名为 'Fruit' 的列,它具有以下三个值:
ID | Fruit |
010 | Apple |
020 | Orange |
010 | Pear |
假设还有其他列,例如 Profile_ID。我如何让 table 改为这样读取,其中一列中的值现在是它们自己的列,并且当配置文件与给定水果相关联时,它将显示 'X' 在该行中:
ID | Apple | Orange | Pear
010 | x | | x
020 | | x |
您可以使用条件聚合。如果您想要一个特定的配置文件 ID,则:
select id,
max(case when fruit = 'Apple' and profile_id = ? then 'X' end) as apple,
max(case when fruit = 'Orange' and profile_id = ? then 'X' end) as orange,
max(case when fruit = 'Pear' and profile_id = ? then 'X' end) as pear
from t
group by id;
如果您只想知道某行是否存在:
select id,
max(case when fruit = 'Apple' then 'X' end) as apple,
max(case when fruit = 'Orange' then 'X' end) as orange,
max(case when fruit = 'Pear' then 'X' end) as pear
from t
group by id;
以下适用于 BigQuery 标准 SQL 并且足够通用以处理任意数量的不同“水果”并且不需要手动输入和明确提及所有这些
EXECUTE IMMEDIATE (
SELECT """
SELECT id, """ ||
STRING_AGG("""MAX(IF(Fruit = '""" || Fruit || """', 'X', '')) AS """ || Fruit, ', ')
|| """
FROM `project.dataset.table`
GROUP BY id
"""
FROM (
SELECT DISTINCT Fruit
FROM `project.dataset.table`
ORDER BY Fruit
)
);
如果应用于您问题中的示例数据 - 输出为
Row id Apple Orange Pear
1 010 X X
2 020 X