我对 PostgreSQL 很陌生,最近在我的项目中,我遇到了检索一年中特定一周的所有记录的问题。主要问题当然是边界周(1 和 52/53)。
为此,我编写了一个函数:
CREATE OR REPLACE FUNCTION week_dates(_week integer, _year integer) RETURNS date[] AS $$
DECLARE
result date[];
BEGIN
WITH RECURSIVE dates(wdate) AS (
SELECT MAX(date) AS wdate FROM time WHERE woy = _week AND year = _year AND dow > 3
UNION ALL
SELECT wdate-1 AS wdate FROM dates WHERE EXTRACT(WEEK from (wdate-1)) = _week
),
dates2(wdate) AS (
SELECT MAX(wdate) AS wdate FROM dates
UNION ALL
SELECT wdate+1 AS wdate FROM dates WHERE EXTRACT(WEEK from (wdate+1)) = _week
),
sorted AS ((SELECT * FROM dates) UNION (SELECT * FROM dates2) ORDER BY wdate ASC)
-- sorted AS (SELECT wdate FROM dates ORDER BY wdate ASC)
SELECT array_agg(wdate) INTO result FROM sorted;
-- SELECT wdate FROM sorted;
RETURN result;
END;
$$ LANGUAGE plpgsql;
它的用法是,例如:
SELECT * FROM "some_report_cache_table" WHERE "date" = ANY(week_dates(1, 2013));
是否有更好/更快/更简单的解决方案(可能是一些内置功能)?
我正在使用 PostgreSQL 9.2,按周我是指一年中的 ISO 周(从星期一开始)