Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query to calculate Previous Week

Tags:

mysql

I would like to calculate my total order amount in the previous week.

I got the query for getting the data for the last 7 days from the current date.

SELECT SUM(goods_total) AS Total_Amount  FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 7 day);

Now how can I get Previous week data only, excluding this week.

For e.g. This week I made $15,000 and last week i made $14,000.

I get the $15,000 by running the above query.

But i dont know how to calculate previous week.

like image 358
Ibn Saeed Avatar asked Dec 10 '25 15:12

Ibn Saeed


1 Answers

Based on the additional information you gave in Alex's answer, I guess the following may work:

SELECT SUM(goods_total) AS Total_Amount, "Previous week" AS Week FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 14 day) 
AND order_placed_date < date_sub(current_date, INTERVAL 7 day)
UNION
SELECT SUM(goods_total) AS Total_Amount, "This week" AS Week FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 7 day) 

This should return two rows and two columns, with a total amount for each of the weeks.

like image 100
Alistair Knock Avatar answered Dec 12 '25 21:12

Alistair Knock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!