UNION和BETWEEN日期

时间:2016-02-26 17:30:52

标签: postgresql

我有两张桌子,人和轮班,我想要的每个人 获得一周的所有班次。 问题是每个日期都不必转换。 如果没有班次,我想获得一个动态模板结果,其中没有班次可用的日期

SELECT p.id, p.name, s.date_of_shift
FROM people AS p
LEFT JOIN LATERAL (
    SELECT sh.id, sh.date_of_shift, sh.person_id
    FROM shifts as sh
) AS s ON p.id = s.person_id
WHERE p.id = 2 AND s.date_of_shift BETWEEN '2016-03-21' AND '2016-03-25'
UNION ALL
SELECT null, null, '2016-03-21'
WHERE NOT EXISTS (
    SELECT 1
    FROM people AS p
    LEFT JOIN LATERAL (
        SELECT sh.id, sh.date_of_shift, sh.person_id
        FROM shifts AS sh
    ) AS s ON p.id = s.person_id
    WHERE p.id = 88000 AND s.date_of_shift BETWEEN  '2016-03-21' AND '2016-03-25');

这是我设法创建的查询。问题是我总是得到相同的日期。但我希望日期在没有转变的范围之间。

1 个答案:

答案 0 :(得分:1)

在这种情况下,您希望某个范围内的所有日期,即使特定日期可能没有数据,您也应该使用generate_series() functionLEFT JOIN数据:< / p>

SELECT DISTINCT p.id, p.name, date_of_shift
FROM generate_series('2016-03-21'::date, '2016-03-25', interval '1 day') AS d(date_of_shift)
LEFT JOIN shifts sh USING (date_of_shift)
LEFT JOIN (SELECT id, name FROM person WHERE id = 2) p ON p.id = sh.person_id;

<强> SQLFiddle