Calculate closest working day in Postgres

后端 未结 4 1074
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 13:24

I need to schedule some items in a postgres query based on a requested delivery date for an order. So for example, the order has a requested delivery on a Monday (20120319

4条回答
  •  再見小時候
    2021-01-05 13:55

    SELECT y.d AS prep_day
    FROM  (
        SELECT generate_series(dday - 8, dday - 1, interval '1d')::date AS d
        FROM (SELECT '2012-03-19'::date AS dday) x
        ) y
    LEFT   JOIN holiday h USING (d)
    WHERE  h.d IS NULL
    AND    extract(isodow from y.d) < 6
    ORDER  BY y.d DESC
    LIMIT  1;
    
    • It should be faster to generate only as many days as necessary. I generate one week prior to the delivery. That should cover all possibilities.

    • isodow as extract parameter is more convenient than dow to test for workdays.

    • min() / max(), ORDER BY / LIMIT 1, that's a matter of taste with the few rows in my query.

    • To get several candidate days in descending order, not just the top pick, change the LIMIT 1.

    • I put the dday (delivery day) in a subquery so you only have to input it once. You can enter any date or timestamp literal. It is cast to date either way.

提交回复
热议问题