I have a view that queries sales data into a condensed table which sums net_sales for each location. The problem i have is when there are sales after midnight. My code is grouping by Date so any sales after midnight are listed on the wrong day.
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;
There is another column in sales_employee (orderhour) which is bigint from 0-23. The system shuts down at 4am so what i need to do is collect sales from orderhour[4] through orderhour[3] and apply the sales of orderhour[0-3] to the previous date. Can that be done?
2
Answers
Whereever you use the date, use:
instead. Subtracting four hours moves transactions between 00:00 and 04:00 to one day earlier. So for example:
I tried modifying your
SQL
query to allocate sales made between midnight and 4 AM to the previous day, using aCASE
statement to adjust the date based on theorderhour
column. Give it a try