Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group by month and year when only having a datetime field?

Tags:

sql

php

mysql

I have a table schema which is essentially a bunch of transaction info with a datetime field

TRANSACTION (< transactionid >, amount, when)

I need to generate a monthly total of transactions, which is SUM(amount), but I stumped by what do I group by. Each row from SQL should contain the monthly total (so one row for Jan 09, Feb 09....Jan 2010 and so on). I am thinking that I may have to generate the table by code, but would like to learn if there is a way to resolve this using SQL.

Any help would be appreciated! (Using MySQL 5.3, PHP5)

like image 413
Extrakun Avatar asked Oct 13 '09 09:10

Extrakun


People also ask

How do I group by year in a date column?

You simply use the aggregate function (here: SUM ) with the correct column and at the end of the query you group by year . You can rename the column using the AS keyword with a new name. In this solution, you don't use a GROUP BY clause. You can read more about the window functions here.

How do you get the month from a timestamp field?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column.

How do I group data by month in Excel?

Right-Click on any cell within the Dates column and select Group from the fly-out list. Then select Month in the dialog box. Using the Starting at: and Ending at: fields, you can even specify the range of dates that you want to group if you don't want to group the entire list.

How do I select month and year in SQL?

There are two SQL function to do it: DATEPART() YEAR() and MONTH().


2 Answers

You need to group by extracts.

SELECT 
    SUM(amount)
FROM 
    transaction
GROUP BY 
    EXTRACT(MONTH FROM when),
    EXTRACT(YEAR FROM when)

And if you need those columns, then

SELECT
    EXTRACT(MONTH FROM when) as month, 
    EXTRACT(YEAR FROM when) as year, 
    SUM(amount)
FROM 
    transaction
GROUP BY 
    month,
    year

Of course you can append ORDER BY and use short names too:

SELECT 
    EXTRACT(MONTH FROM when) as month, 
    EXTRACT(YEAR FROM when) as year, 
    SUM(amount)
FROM 
    transaction
GROUP BY 
    month, 
    year
ORDER BY 
    year DESC, 
    month DESC
like image 107
prostynick Avatar answered Sep 17 '22 14:09

prostynick


    SELECT EXTRACT(YEAR_MONTH FROM when), sum(amount)
      FROM TRANSACTION
  GROUP BY EXTRACT(YEAR_MONTH FROM when)
like image 23
manji Avatar answered Sep 20 '22 14:09

manji