Group by month

Hi all,

I have a query that is grouping data by month and year:

SELECT DATE_FORMAT(t.date_trans, '%b %Y') as date_trans
, CASE WHEN t.type_id = 1 THEN SUM(t.amount) ELSE 0 END as 'income'
, CASE WHEN t.type_id = 2 THEN SUM(t.amount) ELSE 0 END as 'expenses'
FROM trans t
GROUP BY  DATE_FORMAT(t.date_trans, '%b %Y')
ORDER BY t.date_trans

This works fine, but if I have type_id = 1 and type_id = 2 in the same month, then the query returns:

date_trans | income | expenses
Jan 2010    | 10        | 0
Jan 2010    | 0          | 5

Instead, what I need is:

date_trans | income | expenses
Jan 2010    | 10        | 5
LVL 8
JonoBBAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Patrick MatthewsCommented:
Please check your SQL statement, because the SQL statement in your question appears to be correct for returning the single row per month...
0
JonoBBAuthor Commented:
Ugh, seems like I have to swap where the SUM is placed.

This works:

SELECT DATE_FORMAT(t.date_trans, '%b %Y') as date_trans
, SUM(CASE WHEN t.type_id = 1 THEN t.amount ELSE 0 END) as 'income'
, SUM(CASE WHEN t.type_id = 2 THEN t.amount ELSE 0 END) as 'expenses'
FROM trans t
GROUP BY  DATE_FORMAT(t.date_trans, '%b %Y')
ORDER BY t.date_trans
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.