Jump to content

Group by month


Jonob

Recommended Posts

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.utc_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

 

 

Any help appreciated.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.