迁移到标准 SQL:选择离当前日期最近的星期日

Migrate to Standard SQL: choose the closest sunday from current date

我需要从 legacy 迁移到 standard SQL 此查询:

SELECT MAX(FECHA)
FROM(
SELECT FECHA, DAYOFWEEK(FECHA) AS DIA
FROM(
SELECT DATE(DATE_ADD(TIMESTAMP("2017-05-29"), pos - 1, "DAY")) AS FECHA
FROM (
     SELECT ROW_NUMBER() OVER() AS pos, *
     FROM (
       FLATTEN((
         SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), 
         TIMESTAMP("2017-05-29")), '.'),'') AS h
         FROM (SELECT NULL)),h
)))
))
WHERE DIA=1

查询必须return距当前日期最近的星期日。

当我在标准 运行 中 SQL 我得到

Syntax error: Expected keyword JOIN but got ")" at [12:2] (after FROM (SELECT NULL)),h

The query must return the previous closest sunday date from current date.

#standardSQL
SELECT 
  DATE_SUB(CURRENT_DATE(), INTERVAL EXTRACT(DAYOFWEEK FROM CURRENT_DATE()) - 1 DAY)

您可以将 CURRENT_DATE() 替换为任何日期,它将 return 前一个最近的星期日

您可以使用 DATE_TRUNCWEEK 部分来截断到最近的星期日。例如:

#standardSQL
WITH Input AS (
  SELECT date
  FROM UNNEST([
    DATE '2017-06-26',
    DATE '2017-06-24',
    DATE '2017-05-04']) AS date
)
SELECT
  date,
  FORMAT_DATE('%A', date) AS dayofweek,
  DATE_TRUNC(date, WEEK) AS previous_sunday
FROM Input;

这个returns:

+------------+-----------+-----------------+
|    date    | dayofweek | previous_sunday |
+------------+-----------+-----------------+
| 2017-06-24 | Saturday  |      2017-06-18 |
| 2017-05-04 | Thursday  |      2017-04-30 |
| 2017-06-26 | Monday    |      2017-06-25 |
+------------+-----------+-----------------+