PostgreSQL:查看调整基于小时的日期

olhwl3o2  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(2)|浏览(115)

我有一个视图,将销售数据查询到一个压缩表中,该表汇总每个位置的net_sales。我遇到的问题是午夜之后有销售。我的代码是按日期分组的,因此午夜之后的任何销售都列在错误的日期。

SELECT r.name AS store,
r.id,
date(se.date) AS date,
c.dow,
c.week,
c.period,
c.year,
sum(se.netsales) AS net_sales,
sum(se.numberofguests) AS guest_count
FROM sales_employee se
JOIN restaurants r ON r.locationid::text = se.location
JOIN calendar c ON c.date = date(se.date)
GROUP BY r.name, r.id, (date(se.date)), c.dow, c.week, c.period, c.year
ORDER BY (date(se.date)) DESC, r.name;

字符串
sales_employee(orderhour)中还有一列是bigint,从0到23。系统在凌晨4点关闭,所以我需要做的是收集orderhour[4]到orderhour[3]的销售额,并将orderhour[0-3]的销售额应用到前一个日期。这可以做到吗?

cl25kdpy

cl25kdpy1#

我尝试修改SQL查询,将午夜到凌晨4点之间的销售额分配到前一天,并使用CASE语句根据orderhour列调整日期。给予尝试

SELECT
        r.name AS store,
        r.id,
        CASE 
            WHEN se.orderhour >= 4 THEN date(se.date)
            ELSE date(se.date) - interval '1 day'
        END AS adjusted_date,
        c.dow,
        c.week,
        c.period,
        c.year,
        sum(se.netsales) AS net_sales,
        sum(se.numberofguests) AS guest_count
    FROM
        sales_employee se
    JOIN
        restaurants r ON r.locationid::text = se.location
    JOIN
        calendar c ON c.date = CASE 
                                 WHEN se.orderhour >= 4 THEN date(se.date)
                                 ELSE date(se.date) - interval '1 day'
                               END
    GROUP BY
        r.name, r.id, adjusted_date, c.dow, c.week, c.period, c.year
    ORDER BY
        adjusted_date DESC, r.name;

字符串

mwg9r5ms

mwg9r5ms2#

无论在何处使用日期,请使用:用途:

(datecolumn - interval '4 hours')::date

字符串
而不是。减去四个小时会将00:00和04:00之间的事务移动到前一天。例如:

JOIN calendar c ON c.date = date(se.date - interval '4 hours')

相关问题