shelbypereira
shelbypereira

Reputation: 2245

mysql sum only specific groups of a table

Is there a way to sum only specific groups of a table? for example if I have

KEYS  /  VALS
A     /   1
A     /   2
B     /   3
B     /   3 
C     /   1
C     /   1

and I want to get by grouping only A and C but not any others such as B above:

KEYS  /  VALS
A     /   3
B     /   3
B     /   3 
C     /   2

This seems straightforward with a stored proc but I am not sure if it is possible with a query?

Upvotes: 0

Views: 40

Answers (3)

NikuNj Rathod
NikuNj Rathod

Reputation: 1658

Please try below queries

SELECT keys, SUM(vals) as vals
FROM yourtable
WHERE keys in ('A','C')
GROUP BY keys

Upvotes: 0

Shadow
Shadow

Reputation: 34294

It is only possible to achieve this outcome using a union because any group by will apply to the entire resultset. With union you can combine 2 independent queries, therefore the group by will only apply to 1 of the queries:

select keys, sum(vals) as vals
    from yourtable
    where keys in ('A','B')
    group by keys
union
select keys, vals
    from yourtable
    where keys not in ('A','B')

Upvotes: 0

jarlh
jarlh

Reputation: 44795

UNION ALL the non-B part with the B part:

select keys, sum(vals)
from tablename
where keys <> 'B'
group by keys
union all
select keys, vals
from tablename
where keys = 'B'

Upvotes: 3

Related Questions