Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select per month

Tags:

sql

mysql

I've got the following table:

purchases(id, item, user, price, time);

The time field is a timestamp.

I need a query that would return one row per month and that row would contain the sum of price for each item in that month.

like image 874
Emanuil Rusev Avatar asked Oct 06 '10 11:10

Emanuil Rusev


People also ask

How do I select data for a month?

To select all entries from a particular month in MySQL, use the monthname() or month() function. The syntax is as follows. Insert some records in the table using insert command. Display all records from the table using select statement.

What select * means?

SELECT == It orders the computer to include or select each content from the database name(table ) . (*) == means all {till here code means include all from the database.} FROM == It refers from where we have to select the data.

What does select one mean?

The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.


2 Answers

Try this:

SELECT MONTH(`time`) AS month, SUM(price) AS price
FROM your_table
GROUP BY MONTH(`time`)

If you have more than one year's data you may also want to include the year in your group by:

SELECT YEAR(`time`) AS year, MONTH(`time`) AS month, SUM(price) AS price
FROM your_table
GROUP BY YEAR(`time`), MONTH(`time`)
like image 110
Mark Byers Avatar answered Oct 05 '22 23:10

Mark Byers


what about GROUP BY YEAR(DATE(time)) ASC, MONTH(DATE(time)) ASC?

like image 38
Benoit Avatar answered Oct 06 '22 00:10

Benoit