sql select查询结果汇总

时间:2019-10-30 12:39:32

标签: sql

您好,我需要选择查询。

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

查询只能将x和y相加。不是其他人。 (下面的示例)

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

3 个答案:

答案 0 :(得分:2)

您要进行条件分组:

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);

答案 1 :(得分:1)

您可以使用case表达式:

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) ;

答案 2 :(得分:1)

那联盟呢?

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')