google-bigquery - 将行转置为列和对应的值 BigQuery
问题描述
我有一张桌子
WITH table1 AS (
SELECT '2020-12-01 00:00:06 UTC' datetime, 'FuelRate' type, 'l/h' unit, 30.1 Value, 24.1998842 lat, 40.3261354 lon UNION ALL
SELECT '2020-12-01 00:00:06 UTC', 'EngineSpeed', 'rpm', 1850, 24.1998842, 40.3261354 UNION ALL
SELECT '2020-12-01 00:00:06 UTC', 'OutdoorTemp', 'C', -1.0, 24.1998842, 40.3261354 UNION ALL
SELECT '2020-12-01 00:00:06 UTC', 'FuelLevel', 'L', 78.4, 24.1998842, 40.3261354 UNION ALL
SELECT '2020-12-01 00:00:06 UTC', 'HRSengineHours', 'h', 1560, 24.1998842, 40.3261354
)
select * from table1
目前看起来像这样:
但所需的输出将如下所示:
这是我的查询:
SELECT *,
IF(type = 'FuelRate', val, NULL) AS FuelRate_l_h,
IF(type = 'EngineSpeed', val, NULL) AS EngineSpeed_rpm,
IF(type = 'OutdoorTemp', val, NULL) AS OutdoorTemp_C,
IF(type = 'FuelLevel', val, NULL) AS FuelLevel_L,
IF(type = 'HRSengineHours', val, NULL) AS HRSengineHours_h,
FROM table1,
UNNEST(['Value']) col,
UNNEST([CASE col
WHEN 'Value' THEN Value
END]) val
GROUP BY 1,2,3,4,5,6,7,8
但结果如下所示:
我究竟做错了什么?感谢帮助!
解决方案
以下是 BigQuery 标准 SQL
execute immediate (select 'select datetime, ' || string_agg(
'max(if(type="' || type || '",value,null)) ' || type || '_' || replace(unit,'/','_'),', '
) || ', lat, lon from table1 group by datetime, lat, lon '
from (select distinct type, '_' || replace(unit, '/', '_') as unit from table1)
);
如果适用于您的问题的样本数据 - 输出是
推荐阅读
- javascript - 如何通过文件加载器将图像加载为多个页面的背景图像
- javascript - 用围绕该单词的 span 标签替换所有出现的单词。不区分大小写
- reactjs - 如何在 React 点击按钮时发出 API 请求
- sql-server - 使用 scope_identity 多插入如何?
- java - 是否可以添加类似 shebang 的东西来使 jar 文件在 Windows 上可执行?
- ios - 在将视图添加到视图树之前如何计算 UIViewController 高度?
- swift - 多选行swift
- android - 在底部导航中的文本标签后添加图标
- url - 如何在不知道它们的情况下获取 URL 的子页面?
- javascript - Javascript:如何通过`=`符号将setter分配给对象?