willdanceforfun
willdanceforfun

Reputation: 11240

Getting this sql query right with counting and grouping

I am having trouble trying to get this query right.

Say I have a table with the following data:

id    |   xyz     |   code
===========================
1     |    1      |    ba
2     |    1      |    zz
3     |    1      |    ba
1     |    1      |    zz
1     |    1      |    ba
2     |    1      |    zz

And I'd like to get a sum of 'xyz', grouped by id e.g.

SELECT id, SUM(xyz) as mysum FROM table WHERE xyz=1 GROUP BY id

I would end up with the results:

id   |  mysum 
================
1    |  3
2    |  2
3    |  1

Perfect.

The thing is, what I'd actually like to do is group by the 'code' column as well, so that if say for id: 1, which has 2 entries with the code 'ba', then the result would be more like this:

id   |  mysum 
================
1    |  2
2    |  1
3    |  1

Here is where my limited understanding of mysql fails me. Because I would think to do a query like this:

SELECT id, SUM(xyz) AS mysum FROM table WHERE xyz=1 GROUP BY id, code

But this clearly gives the results I'm not after.

How can I do this sort of query that does a SUM of column xyz, while omitting it if it has already added one that has the same 'code'?

Upvotes: 0

Views: 81

Answers (2)

John Woo
John Woo

Reputation: 263713

SELECT id,
       SUM(CASE WHEN code = 'ba' then 1 ELSE 0 END)
FROM table1
GROUP BY id

follow-up question: why does id=2 has a value of 1, isn't it zero?

UPDATE 1

SELECT id,
       count(Distinct code)
FROM table1
GROUP BY id

Upvotes: 2

Saddam Abu Ghaida
Saddam Abu Ghaida

Reputation: 6729

SELECT code,SUM(xyz) FROM table GROUP BY code,xyz

Upvotes: 0

Related Questions