Bigquery:如何将2个时间戳列合并为1个列?

时间:2019-01-27 08:06:17

标签: google-bigquery standard-sql

有人知道如何从Google Bigquery中的两个时间戳列中创建一个时间戳列吗?

我有一个包含两个时间戳列的表,我想将这两列合并为一个列。该表当前如下所示:

@ManyToMany

所以...我正在尝试将这两个时间戳列合并为一列。我的预期结果如下:

id  | user_id | created_at_a             | created_at_b
------------------------------------------------------------------
1   | 1       | 2019-01-24 12:20:00 UTC  | 2019-01-25 01:04:00 UTC
2   | 1       | 2019-01-24 12:20:00 UTC  | 2019-01-25 01:03:00 UTC
3   | 1       | 2019-01-24 12:22:00 UTC  | 2019-01-25 01:03:00 UTC
4   | 1       | 2019-01-24 12:22:00 UTC  | 2019-01-25 01:04:00 UTC
5   | 2       | 2019-01-24 20:48:00 UTC  | 2019-01-24 20:49:00 UTC
6   | 2       | 2019-01-24 11:21:00 UTC  | 2019-01-24 20:49:00 UTC

请人请我帮忙。

非常感谢!

1 个答案:

答案 0 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT DISTINCT user_id, created_at
FROM (
  SELECT user_id, 
    ARRAY_CONCAT_AGG([created_at_a, created_at_b]) created_at_ab
  FROM `project.dataset.table`
  GROUP BY user_id
), UNNEST(created_at_ab) created_at

您可以使用以下问题中的示例数据来测试,玩这个游戏

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, 1 user_id, TIMESTAMP '2019-01-24 12:20:00 UTC' created_at_a, TIMESTAMP '2019-01-25 01:04:00 UTC' created_at_b UNION ALL
  SELECT 2, 1, '2019-01-24 12:20:00 UTC', '2019-01-25 01:03:00 UTC' UNION ALL
  SELECT 3, 1, '2019-01-24 12:22:00 UTC', '2019-01-25 01:03:00 UTC' UNION ALL
  SELECT 4, 1, '2019-01-24 12:22:00 UTC', '2019-01-25 01:04:00 UTC' UNION ALL
  SELECT 5, 2, '2019-01-24 20:48:00 UTC', '2019-01-24 20:49:00 UTC' UNION ALL
  SELECT 6, 2, '2019-01-24 11:21:00 UTC', '2019-01-24 20:49:00 UTC' 
)
SELECT DISTINCT user_id, created_at
FROM (
  SELECT user_id, 
    ARRAY_CONCAT_AGG([created_at_a, created_at_b]) created_at_ab
  FROM `project.dataset.table`
  GROUP BY user_id
), UNNEST(created_at_ab) created_at
-- ORDER BY user_id, created_at   

有结果

Row user_id created_at   
1   1   2019-01-24 12:20:00 UTC  
2   1   2019-01-24 12:22:00 UTC  
3   1   2019-01-25 01:03:00 UTC  
4   1   2019-01-25 01:04:00 UTC  
5   2   2019-01-24 11:21:00 UTC  
6   2   2019-01-24 20:48:00 UTC  
7   2   2019-01-24 20:49:00 UTC