tags:

views:

962

answers:

6

Hello

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.

A: 

The easiest way to do this would be to use mysql Date and Time Functions

WEEKOFYEAR()

joe
A: 

You can use DATE_SUB().

Sinan Taifour
A: 

Try:

SELECT SUM(goods_total) AS Total_Amount  FROM orders
WHERE order_placed_date >= date_sub(current_date, INTERVAL 14 day) 
AND order_placed_date < date_sub(current_date, INTERVAL 7 day);
Alistair Knock
+1  A: 

If you want "rolling weeks" (sliding 7-days-long windows) instead of weeks starting on Sunday (or other specific weekdays),

SELECT SUM(goods_total) AS Total_Amount FROM orders
WHERE order_placed_date BETWEEN
 date_sub(current_date, INTERVAL 14 day) AND
 date_sub(current_date, INTERVAL 8 day);
Alex Martelli
This is also useful. But I would like to track from today to last 7 days ( For this week), and from the last 7 days to further 7 days for the previous week.
Ibn Saeed
You mean, you want weeks to overlap by one day? Or are you implying `excluded` in either the "to" or "from" parts of your sentence? BETWEEN does `included` so it needs care.
Alex Martelli
I want to calculate Last week starting from todays date and going back. I dont need weeks such as 1st to 7th and so .
Ibn Saeed
...and the query I supply does exactly what you say you want (so does Alistair's, using < and >= instead of BETWEEN).
Alex Martelli
A: 

What about the following query:

SELECT   count(order_placed_date) 
FROM     orders
WHERE    YEARWEEK(order_placed_date) = YEARWEEK(CURRENT_DATE - INTERVAL 7 DAY)
Ibn Saeed
I suspect you need a date_sub like YEARWEEK(date_sub(CURRENT_DATE - INTERVAL 7 DAY))
lexu
My above version works fine, your version also works but by removing " - " and replacing it withe a comma " , " --------------YEARWEEK(date_sub(CURRENT_DATE, INTERVAL 7 DAY))
Ibn Saeed
ah, I didn't know that! thx!
lexu
+1  A: 

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.

Alistair Knock
it works fine thanks
Ibn Saeed