我希望从该月的第一天开始拉每个月的第一个星期三。
SELECT
CASE
WHEN latestRefreshTime => ***first wednesday of every month*** THEN 'Up to Date'
WHEN latestRefreshTime2 => ***last thursday of every month*** THEN 'Up to Date'
ELSE ' Not Up To Date'
END AS upToDate
我尝试使用 DATE_TRUNC(CURRENT_DATE(), MONTH) 来获取该月的第一天,但我很难将其钻取到第一个星期三,并且要使其保持动态,因此每个月都会发生变化。上周四也是同样的事情
希望下面的 BigQuery 示例对您有帮助
WITH days AS (
SELECT CURRENT_DATE AS dt UNION ALL
SELECT '2023-05-22' UNION ALL
SELECT '2023-04-22' UNION ALL
SELECT '2023-03-22'
)
SELECT dt,
IF(EXTRACT(MONTH FROM x) = EXTRACT(MONTH FROM DATE(dt)), x, x - 7) as last_thursday,
IF(EXTRACT(MONTH FROM y) = EXTRACT(MONTH FROM DATE(dt)), y, y + 7) as first_wednesday
FROM(
SELECT dt,
LAST_DAY(LAST_DAY(DATE(dt), MONTH), WEEK(FRIDAY)) x,
LAST_DAY(LAST_DAY(DATE_TRUNC(dt, MONTH) - 1, MONTH), WEEK(THURSDAY)) y
FROM days
)
有输出
您可以使用相应日期当月的第一个星期三和最后一个星期四创建一个中间表,然后应用该规则。
DECLARE arbitrary_date DATE DEFAULT'2023-06-21';
WITH
-- Table with first and last day of the month for each date
first_last_day_table AS (
SELECT
arbitrary_date,
DATE_TRUNC(arbitrary_date, MONTH) AS first_day_month,
DATE_SUB(DATE_TRUNC(DATE_ADD(arbitrary_date, INTERVAL 1 MONTH), MONTH), INTERVAL 1 DAY) AS last_day_month,
)
-- Table with first wednesday and last thursday for each date
SELECT
arbitrary_date,
first_day_month + MOD(11 - EXTRACT(DAYOFWEEK FROM first_day_month), 7) AS first_wednesday,
last_day_month - MOD(2 + EXTRACT(DAYOFWEEK FROM last_day_month), 7) AS last_thursday
FROM first_last_day_table
大查询: 查询该月的第一个星期三:
选择 date_add(DATE_TRUNC(current_date(), MONTH),间隔 (mod(7 - EXTRACT(DAYOFWEEK FROM DATE_TRUNC(current_date(), MONTH)) +4,7)) day)