We have an existing system that has a lot of orders. I want to make a report that will show which days have the most sales from the beginning of the year 01.01.2023 to the current date. We researched examples via stackovefow but it doesn’t give us accurate information.
The report shows that Sunday has the most sales, which is not true. We have the lowest number of sales on weekends, while during working days Monday, Tuesday, Wednesday are the strongest days when we sell the most and then the most are entered into the system.
Can you check and tell me where I made a mistake?
SELECT DAYNAME(o.created_at) day, AVG(o.id) sales
FROM order o
WHERE DAYOFWEEK(o.created_at) AND year(o.created_at) = '2023'
GROUP BY DAYNAME(o.created_at)
ORDER BY DAY(o.created_at)
Tables:
order
id INT PK AI
number Varchar NotNull
order_type INT
created_at timestamp
order_items
id INT PK AI
product_id ID
order_id INT
qty INT
price DECIMAL
created_at timestamp
product
id INT PK AI
group_id ID
supllier_id INT
name INT
created_at timestamp
etc..
2
Answers
I think the following query provides the result that you want:
This query takes all orders from the order table with dates in the specified year and then determines all order numbers for each day. It then calculates the average number of orders for each day and finally selects the day with the highest average number of orders.
The
DAYNAME()
function is used to determine the name of each day, and theAVG()
function is used to calculate the average number of orders for each day. The results are grouped according to the names of the days, and then arranged in descending order based on the average number of orders using theORDER BY
keyword. Finally, the day with the highest average number of orders is selected with the keywordLIMIT
.You first have to count sales per day, then use
AVG()
on total sales to get the average bydayname
Demo here