BigQuery/SQL:如何使用列值作为列名?
我有这些桌子: 食物 营养素BigQuery/SQL:如何使用列值作为列名?,sql,google-bigquery,Sql,Google Bigquery,我有这些桌子: 食物 营养素 | food_id | nutrient_id | amount | | 1 | n1 | 0.05 | | 1 | n2 | 2 | | 1 | n3 | 34 | ... 我需要这个: | food_id | title | n1 | n2 | n3 | | 1 | soy milk | 0.05 | 2 | 34 | | 2
| food_id | nutrient_id | amount |
| 1 | n1 | 0.05 |
| 1 | n2 | 2 |
| 1 | n3 | 34 |
...
我需要这个:
| food_id | title | n1 | n2 | n3 |
| 1 | soy milk | 0.05 | 2 | 34 |
| 2 | banana | | | |
| 3 | apple | | | |
列标题应该由在“营养素id”列中找到的任何内容表示,而不是由实际字符串n1、n2等表示。例如,如果营养素id是some-nutrient-123,那么我希望在结果中看到标题为some-nutrient-123的列
Struct也可以工作
我知道所有的连接,但我不能绕着这个。。。如何将id的值放入列标题或结构键中?您正在查找类似以下内容的查询:
with t1 as (
SELECT
food_id as id_new,
SUM(CASE WHEN nutrient_id = 'n1' THEN amount END) AS n1,
SUM(CASE WHEN nutrient_id = 'n2' THEN amount END) AS n2,
SUM(CASE WHEN nutrient_id = 'n3' THEN amount END) AS n3
FROM `<Nutrients>`
GROUP BY id_new
ORDER BY id_new
)
SELECT * FROM `<Foods>` as t2 JOIN t1
on t2.id = t1.id_new
现在,我知道您不想硬编码营养素名称。到目前为止,我不确定这在BigQuery中是否可行。我的解决方法是运行例如查询
SELECT
CONCAT(
'SUM(CASE WHEN nutrient_id = "' , nutrient_id , '" THEN amount END) AS ', nutrient_id
)
FROM (
SELECT nutrient_id FROM <Nutrients> GROUP BY nutrient_id ORDER BY nutrient_id
)
热心地遵循所做的事情。这将给你考虑所有的情况。 这可能对你有帮助
SELECT
CONCAT(
'SUM(CASE WHEN nutrient_id = "' , nutrient_id , '" THEN amount END) AS ', nutrient_id
)
FROM (
SELECT nutrient_id FROM <Nutrients> GROUP BY nutrient_id ORDER BY nutrient_id
)