合并两列并创建新行

时间:2018-10-30 09:51:17

标签: google-bigquery

尝试在BQ中将两列合并为一列,

我当前的表格如下:

+-------+--------------------------------------+------+-----+
| id    | time                        | color1 |color2|type |
+-------+--------------------------------------+------+-----+
| 10954 | 2018-09-09 23:20:01.074 UTC | yellow | blue | 1   |
+-------+--------------------------------------+------+-----+
| 10954 | 2018-10-09 20:38:61.151 UTC | red    | blue | 1   |
+-------+--------------------------------------+------+-----+
| 20562 | 2018-08-09 19:49:14.391 UTC | green  | red  | 0   |
+-------+--------------------------------------+------+-----+
| 20562 | 2017-09-09 17:02:22.903 UTC | green  | red  | 1   |
+-------+--------------------------------------+------+-----+

我的目标表将是:

+-------+--------------------------------------+------+
| id    | time                        | color  | type |     
+-------+--------------------------------------+------+
| 10954 | 2018-09-09 23:20:01.074 UTC | yellow |  1   |     
+-------+--------------------------------------+------+
| 10954 | 2018-10-09 20:38:61.151 UTC | red    |  1   |     
+-------+--------------------------------------+------+
| 10954 | 2018-09-09 23:20:01.074 UTC | blue   |  0   |     
+-------+--------------------------------------+------+
| 20562 | 2018-08-09 19:49:14.391 UTC | green  |  0   |     
+-------+--------------------------------------+------+
| 20562 | 2017-09-09 17:02:22.903 UTC | green  |  1   |     
+-------+--------------------------------------+------+
| 20562 | 2017-09-09 17:02:22.903 UTC | red    |  0   |     
+-------+--------------------------------------+------+

这样做,将为color2创建新行,其中id将重复,time将是id组的 min 时间和type = 0。创建新的颜色列或使用CTE时,是否可以在case when语句中执行此操作?

1 个答案:

答案 0 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT id, time, color1 AS color, type
FROM `project.dataset.table`
UNION ALL
SELECT id, MIN(time) AS time, color2 AS color, 0 type
FROM `project.dataset.table`
GROUP BY id, color2

您可以使用下面的问题中的虚拟dta来测试,玩游戏

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 10954 id, '2018-09-09 23:20:01.074 UTC' time, 'yellow' color1, 'blue' color2, 1 type UNION ALL
  SELECT 10954, '2018-10-09 20:38:61.151 UTC', 'red', 'blue', 1 UNION ALL
  SELECT 20562, '2018-08-09 19:49:14.391 UTC', 'green', 'red', 0 UNION ALL
  SELECT 20562, '2017-09-09 17:02:22.903 UTC', 'green', 'red', 1
)
SELECT id, time, color1 AS color, type
FROM `project.dataset.table`
UNION ALL
SELECT id, MIN(time) AS time, color2 AS color, 0 type
FROM `project.dataset.table`
GROUP BY id, color2
-- ORDER BY id 

有结果

Row id      time                        color   type     
1   10954   2018-09-09 23:20:01.074 UTC yellow  1    
2   10954   2018-10-09 20:38:61.151 UTC red     1    
3   10954   2018-09-09 23:20:01.074 UTC blue    0    
4   20562   2018-08-09 19:49:14.391 UTC green   0    
5   20562   2017-09-09 17:02:22.903 UTC green   1    
6   20562   2017-09-09 17:02:22.903 UTC red     0