去年的星期几

时间:2019-07-02 15:34:57

标签: google-bigquery

我正在尝试在标准SQL BigQuery中计算去年同一天的等效日期。

例如,如果当前日期2019-07-01是第27周的星期一。我想知道去年(2018)第27周的星期一的日期。

本周为select extract(isoweek from current_date()) 但我不知道如何使用它来计算日期。

如果当前日期为2019-07-01,则预期输出为2018-07-02

之所以这样做,是因为我想将当前销售额与去年相同的一周和一周中的某天进行比较。

任何建议都值得赞赏。

2 个答案:

答案 0 :(得分:1)

像这样的事情应该会让你前进...

y = 1

上面的查询使用的是从星期一开始的一周,您可能需要使用with dates as (select * from unnest(generate_date_array('2018-01-01','2019-12-31', interval 1 day)) as cal_date), cal as (select cal_date, cast(format_date('%Y', cal_date) as int64) as year, cast(format_date('%V', cal_date) as int64) as week_num, format_date('%A', cal_date) as weekday_name from dates) select c1.cal_date, c1.week_num, c1.weekday_name, c2.cal_date as previous_year_same_weekday from cal c1 inner join cal c2 on c1.year = c2.year+1 and c1.week_num = c2.week_num and c1.weekday_name = c2.weekday_name 参数as seen here来进行修改以适应您的需求。

答案 1 :(得分:1)

此查询不返回任何结果,表明SHIFT有效。如果一年的前一周没有多少周,则该函数返回NULL

CREATE TEMP FUNCTION P_YEAR(y INT64) AS (
  MOD(CAST(y + FLOOR(y / 4.0) - FLOOR(y / 100.0) + FLOOR(y / 400.0) AS INT64), 7)
);

CREATE TEMP FUNCTION WEEKS_YEAR(y INT64) AS (
  52 + IF(P_YEAR(y) = 4 OR P_YEAR(y - 1) = 3, 1, 0)
);

CREATE TEMP FUNCTION SHIFT(d DATE) RETURNS DATE AS (
  CASE
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) != WEEKS_YEAR(EXTRACT(ISOYEAR FROM d) - 1)
      THEN null
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) = 52
      THEN DATE_SUB(d, INTERVAL 52 WEEK)
    ELSE d
  END
);

WITH dates AS (
SELECT d
FROM UNNEST(GENERATE_DATE_ARRAY('2000-12-31', '2020-12-31', INTERVAL 1 DAY)) AS d
)
SELECT
 d,
 EXTRACT(ISOWEEK FROM d) AS orig_iso_week,
 EXTRACT(ISOWEEK FROM SHIFT(d)) AS new_iso_week,
 SHIFT(d) AS new_d
FROM dates
WHERE EXTRACT(ISOWEEK FROM d) != EXTRACT(ISOWEEK FROM SHIFT(d))
  AND SHIFT(d) IS NOT NULL