使用group by查找sql中具有特定列值的列的和

nc1teljy  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(296)

我有一个包含以下列的表:

amount   employee   
100        a
200        a
300        b
400        b
500        c

我想在同一个表中得到一个输出,该表根据雇员“a”和其他人(a除外)进行分组,并根据分组给出金额的总和。期望结果:

amount  employee 
300            a 
1200         rest
kcrjzv8t

kcrjzv8t1#

使用case转换employee值,并对转换后的值进行分组:

SELECT 
    CASE WHEN employee = 'a' THEN 'a' ELSE 'rest' END as e,
  SUM(amount) as a
FROM
  t
GROUP BY
  CASE WHEN employee = 'a' THEN 'a' ELSE 'rest' END

您也可以使用union:

SELECT 
  MAX(emlpoyee) as e,
  SUM(amount) as a
FROM
  t
WHERE employee = 'a'

UNION ALL

SELECT 
  'rest' as e,
  SUM(amount) as a
FROM
  t
WHERE employee <> 'a'

后一种方法可能会更占用资源,但可能更易于理解和维护,因此您需要判断您是看重直接的性能还是对开发人员友好(对于一个每天对100名员工运行一次的查询,你可以说让查询更容易理解会更好。对于一个每秒访问数万名员工的查询,性能应该优先)

vsmadaxz

vsmadaxz2#

请使用下面的查询,

select sum(amount), employee from
(select 
amount, case when employee = 'a' then employee else 'Rest' end as employee
from table t) t1
group by employee;
plicqrtu

plicqrtu3#

使用 case 表达式 group by 密钥:

select (case when employee = 'a' then employee else 'rest' end) as employee,
       sum(amount)
from t
group by (case when employee = 'a' then employee else 'rest' end) ;

这是一把小提琴(这碰巧使用mysql,但这是标准sql,可以在任何数据库中使用。)

相关问题