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.
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.
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.
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.
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`)
what about GROUP BY YEAR(DATE(time)) ASC, MONTH(DATE(time)) ASC
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With