Hello I had an sql getting the number of orders this week. My sample query below:
SELECT products.name,
(SELECT COUNT(orders.product_id)
FROM orders
WHERE orders.product_id = products.id
AND DATE(orders.order_date) >= [from] AND DATE(orders.order_date) [to]) as total_orders
FROM products p;
Now I want also get the total orders from previous week then get total orders from last week substract the orders from this week.
Results would be this
Products | Total Orders This Week | Difference from last and current week |
---|---|---|
Scissors | 6 | 3 |
2
Answers
you could do a function to get those totals. The function will receive
date1
when starts that week, anddate2
when finish that weekThen in your query you only call your function 2 times, the first to get current week orders and the second get the difference between current and last week.
You may use conditional aggregation.
A pattern:
The query uses implicit aggregation (there is no GROUP BY – so the whole source rowset is treated as one group).
The conditions used returns either 0 or 1 depends on the checking result, so
SUM()
acts as counting the amount of TRUE checks.Additional WHERE excludes the rows which will produce FALSE for all conditions, and eliminates excess checkings.