我正在尝试创建一个如下表:
| year | week_number | first_week_day | last_week_day |
-------------------------------------------------------
| 2019 | 1 | 2019-01-01 | 2019-01-07 |
.......................................................
我已经搜索了实现方法,并决定使用EXTRACT和GENERATE_DATE。如果有更好的方法,请告诉我。
这是我到目前为止所拥有的:
#StandardSQL
WITH
dates_2018 AS
(SELECT GENERATE_DATE_ARRAY("2018-01-01", "2018-12-31") AS d_2018)
,dates_2019 AS
(SELECT GENERATE_DATE_ARRAY("2019-01-01", "2019-12-31") AS d_2019)
SELECT un
FROM dates_2018, UNNEST(d_2018) AS un
-- ,timestamps_2018 AS
-- (SELECT TIMESTAMP(dates_2018) AS timestamps_2018
-- FROM UNNEST(dates_2018))
-- ,d_2018 AS
-- (SELECT EXTRACT(year from timestamps_2018) AS year
-- ,EXTRACT(week from timestamps_2018) AS week
-- ,EXTRACT(day from timestamps_2018) AS day
-- FROM timestamps_2018)
-- SELECT *
-- FROM timestamps_2018
我现在的问题在于我无法纠正UNNEST数组d_2018的事实,因此我可以将所有元素转换为时间戳,以便以后可以从中提取内容。
当我取消嵌套时,它仅返回第一行。
主要是我正在寻找这个毫不费力的修复程序,但是如果有人可以提供更多建议,那么它将受到欢迎。
答案 0 :(得分:2)
我不确定您为什么将每年的数据分开。根据您的描述:
WITH dates AS (
SELECT GENERATE_DATE_ARRAY('2018-01-01', '2019-12-31') as date_array
)
select extract(year from d) as year, d,
EXTRACT(week from d) as week,
date_trunc(d, week) as first_week_day,
date_add(date_trunc(d, week), interval 6 day) as last_week_day
from dates cross join
unnest(date_array) d
ORDER BY d;
答案 1 :(得分:0)
UNNEST
将数组条目转换为表行,以便您可以在它们上运行SQL。
我不确定您要做什么,但是您完全可以做类似的事情
SELECT
d,
extract(WEEK from d) CW,
extract(DAY from d) day,
extract(YEAR from d) year
FROM UNNEST(GENERATE_DATE_ARRAY("2018-01-01", "2019-12-31")) AS d
将generate_date_array()
中的数组输入unnest()
答案 2 :(得分:0)
以下是用于BigQuery标准SQL
#standardSQL
SELECT DISTINCT
EXTRACT(YEAR FROM day) AS year,
EXTRACT(WEEK FROM day) + 1 AS week_number,
DATE_TRUNC(day, WEEK) AS first_week_day,
DATE_ADD(DATE_TRUNC(day, week), INTERVAL 6 DAY) AS last_week_day
FROM UNNEST(GENERATE_DATE_ARRAY('2018-01-01', '2019-12-31')) AS day