简体   繁体   中英

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

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)

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
    SELECT EXTRACT(YEAR_MONTH FROM when), sum(amount)
      FROM TRANSACTION
  GROUP BY EXTRACT(YEAR_MONTH FROM when)

I've always used MONTH() and YEAR()...which seems a little bit like a Hack to me, but it works...

SELECT SUM(amount) FROM yourTable GROUP BY MONTH(date), YEAR(date)

Or was it the other way round? thinks

Bobby

I would try something like that:

SELECT
  YEAR(when) AS year,
  MONTH(when) AS month,
  SUM(amount) AS amount
FROM
  TRANSACTION
GROUP BY
  YEAR(when),
  MONTH(when)
ORDER BY
  YEAR(when),
  MONTH(when)

This works on MS SQL and should work on MySQL too.

I think you want:

SELECT SUM(amount)
FROM yourTable
GROUP BY CONCAT(YEAR(date), '-', MONTH(date))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM