lewisatep
lewisatep

Reputation: 39

sql select query summing the results

hello i need select query.

+--------------------------+
|  A                    B  |
+--------------------------+
| ------------------------ |
| x                    5   |
| y                    10  |
| z                    15  |
| t                    20  |
+--------------------------+

query must only sum x and y . not the others. (example below)

A                    B
------------------------
p(as x+y)            15
z                    15
t                    20

Upvotes: 0

Views: 47

Answers (3)

user330315
user330315

Reputation:

What about a UNION?

select 'p' as a, sum(b) as b
from the_table
where a in ('x','y')

union all

select a, b
from the_table
where a not in ('x','y')

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271211

You can use a case expression:

select (case when a in ('x', 'y') then 'p' else a end) as a,
       sum(b)
from t
group by (case when a in ('x', 'y') then 'p' else a end) ;

Upvotes: 1

Yogesh Sharma
Yogesh Sharma

Reputation: 50173

You want conditional grouping :

select (case when a in ('x', 'y') then 'p' else a end) as a, sum(b) as b
from table t
group by (case when a in ('x', 'y') then 'p' else a end);

Upvotes: 2

Related Questions