在BigQuery中,我们可以使用unnest函数来展开嵌套的数组,将其转换为单个行。如果我们想在时间戳间隔中展开值,我们可以使用EXTRACT函数来提取所需的时间单位并将其转换为扁平结构。
例如,假设我们有一个包含时间戳范围的表,如下所示:
+------+---------------------+---------------------+
| id | start_time | end_time |
+------+---------------------+---------------------+
| 1 | 2022-01-01 00:00:00 | 2022-01-01 01:00:00 |
| 2 | 2022-01-01 02:00:00 | 2022-01-01 03:00:00 |
+------+---------------------+---------------------+
我们想将每个值展开为单个行,因此我们需要执行以下操作:
使用TIMESTAMP_DIFF计算时间戳之间的差异,并将其转换为秒数。
使用UNNEST展开由EXTRACT函数生成的时间戳值数组。
使用TIMESTAMP_ADD函数将开始时间和间隔相加以获取结束时间。
下面是执行上述操作的代码:
WITH intervals AS (
SELECT 1 AS id, TIMESTAMP('2022-01-01 00:00:00') AS start_time, TIMESTAMP('2022-01-01 01:00:00') AS end_time UNION ALL
SELECT 2 AS id, TIMESTAMP('2022-01-01 02:00:00') AS start_time, TIMESTAMP('2022-01-01 03:00:00') AS end_time
),
interval_secs AS (
SELECT
id,
DATE_DIFF(DATE(start_time), DATE('1970-01-01'), DAY) * 86400 + UNIX_SECONDS(start_time) AS start_secs,
DATE_DIFF(DATE(end_time), DATE('1970-01-01'), DAY) * 86400 + UNIX_SECONDS(end_time) AS end_secs
FROM intervals
),
interval_arr AS (
SELECT
id,
ARRAY(
SELECT start_secs + (i-1) * 3600
FROM UNNEST(GENERATE_ARRAY(1, (end_secs-start_secs)/3600+1)) AS i)
AS timestamp_values
FROM interval_secs
)
SELECT
id,
TIMESTAMP_SECONDS(timestamp_value) AS timestamp_value
FROM interval_arr, UNNEST(timestamp_values) AS timestamp_value;
``