troubleshooting Question

Group by month

Avatar of JonoBB
JonoBB asked on
DatabasesMySQL ServerSQL
2 Comments1 Solution400 ViewsLast Modified:
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
ASKER CERTIFIED SOLUTION
JonoBB

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros