【发布时间】:2021-08-04 18:11:43
【问题描述】:
假设我有一张这样的桌子:
| id | brand | fuel | mpg |
|:--:|:------:|:------:|:---:|
| 1 | ford | diesel | 14 |
| 1 | ford | gas | 20 |
| 1 | toyota | diesel | 30 |
| 1 | toyota | gas | 35 |
我希望旋转列,结果如下:
| id | ford | toyota | toyota_mpg | ford_mpg |
|:--:|:------:|--------|:----------:|:--------:|
| 1 | diesel | diesel | 30 | 14 |
| 1 | gas | gas | 35 | 20 |
| 1 | diesel | gas | 35 | 14 |
| 1 | gas | diesel | 30 | 20 |
到目前为止,我已经
SELECT id,
MAX(CASE WHEN end_use = 'ford' THEN fuel ELSE NULL END) ford,
SUM(CASE WHEN end_use = 'ford' THEN mpg ELSE NULL END) ford_mpg,
MAX(CASE WHEN end_use = 'toyota' THEN fuel ELSE NULL END) toyota,
SUM(CASE WHEN end_use = 'toyota' THEN mpg ELSE NULL END) toyota_mpg,
FROM table GROUP BY id, fuel
结果如下,当燃料对齐时给我正确的结果:
| id | ford | toyota | toyota_mpg | ford_mpg |
|:--:|:------:|--------|:----------:|:--------:|
| 1 | diesel | diesel | 30 | 14 |
| 1 | gas | gas | 35 | 20 |
但我无法获得燃料组合(它们不匹配的地方)。
【问题讨论】:
标签: sql google-bigquery pivot case