tags:

views:

1190

answers:

3

Hello

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

I got the query for getting the data for the present month from the current date.

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

Now how can I get Previous Months Data only, excluding this month.

For e.g. This month (July) I made $15,000 and last Month(June) i made $14,000.

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

But i dont know how to calculate Previous Months.

+3  A: 

Here you go, use this to get the date between the 1st of last month and the last of last month in MySQL:

... order_placed_date BETWEEN date_format(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') AND last_day(NOW() - INTERVAL 1 MONTH)

Artem Russakovskii
You're welcome. I had the same problem a few months back and came up with that.
Artem Russakovskii
Thank you it worked perfectly, the result matched my data.
Ibn Saeed
I am using current_date instead of NOW()
Ibn Saeed
NOW() is the same as CURRENT_TIMESTAMP, which really here is the same as CURRENT_DATE.
Artem Russakovskii
So theres no difference in using NOW() in place of current_date in terms of performance
Ibn Saeed
Yeah, all it does is give a reference point in calculating the dates, so it doesn't matter.
Artem Russakovskii
A: 

If you are lazy it's kinda convenient to use

...date_format(order_placed_date, '%Y-%m') = date_format(now() - INTERVAL 1 MONTH, '%Y-%m')

I think it also increases readability.

The problem with your query is that it will do a full table scan and will have horrible performance on large data sets because it will not use an index. The query with BETWEEN that I posted uses a range, so it'll be able to utilize an index. The readability... I think both are readable :)
Artem Russakovskii
Oh and FYI, MySQL doesn't support function based indexes. PostgreSQL supposedly does.
Artem Russakovskii
Sorry, I see that now. I'm just used doing that from tables with up to a couple hundred records. Thanks.
A: 

Here is another way i found:

SELECT SUM(goods_total) AS Total_Amount  FROM orders
WHERE SUBSTRING(o.order_placed_date FROM 1 FOR 7) =   SUBSTRING(CURRENT_DATE - INTERVAL 1 MONTH FROM 1 FOR 7)

This works as well.

Ibn Saeed
Same problem as above, I would think. Run all SELECTs through EXPLAIN (just prepend EXPLAIN to each SELECT) and see what kind of information EXPLAIN gives you about the efficiency of each query.
Artem Russakovskii
That is, assuming you created an index on order_placed_date. You did, right? RIGHT?
Artem Russakovskii
Under Indexes, order_placed_date settings are: Non_Unique = 1, Seq_in_Index = 1, IndexType= BTREE
Ibn Saeed