user1211577
user1211577

Reputation:

MySQL Sum grouping issue

I have a table containing jobs to be invoiced. Each row contains two columns, 'value' and 'group'. Like this

ID   Value  Group
1   2000.00   1
2   2000.00   1
3   1000.00   0
4   1000.00   0

What I need to do is combine the values in Rows 1 and 2 (because they have the same group number), then return rows 3 and 4 as normal (so, not grouped together):

4000    //Rows 1 and 2 combined
1000    //Row 3 returned as whole value
1000    //Row 4 returned as whole value

I've tried to use GROUP BY in the query, so something like

  SELECT SUM(Value) AS totalValue FROM table GROUP BY Group

However this returns

4000
2000 //Row 3 and 4 combined

It's combining Row 3 and 4 because they share the same Group number, its grouping them together.

My problem is, I don't want them grouped together. I want them to return separately as they have a value of zero. Is there any way for me to do this?

Upvotes: 0

Views: 73

Answers (1)

Aziz
Aziz

Reputation: 20715

SELECT Group AS Unique_ID, SUM(Value) AS totalValue FROM table WHERE Group>0 GROUP BY Group
UNION
SELECT id AS Unique_ID, Value As totalValue FROM table WHERE Group=0 

Upvotes: 1

Related Questions