简体   繁体   English

使用 group by 在 SQL 中查找具有特定列值的列的总和

[英]finding sum of a column with specific values of a column in SQL using group by

I have a table with the following columns:我有一个包含以下列的表格:

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

I want to get an output in the same table which groups based on employee 'a' and the rest (other than a ) and gives the sum of the amount, based on grouping.我想在同一张表中获得一个 output ,该表基于员工“a”和 rest (a 除外)进行分组,并根据分组给出金额的总和。 Desired result:期望的结果:

amount  employee 
300            a 
1200         rest 

Use a case expression for the group by key:按键group by使用case表达式:

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

Here is a db<>fiddle. 是一个 db<>fiddle。 (This happens to use MySQL, but this is standard SQL and will work in any database.) (这恰好使用 MySQL,但这是标准的 SQL,适用于任何数据库。)

Convert the employee values using CASE WHEN and group the converted value:使用 CASE WHEN 转换员工值并将转换后的值分组:

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

You could also use UNION:你也可以使用 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'

This latter way will probably be more resource intensive but may be easier to understand and maintain hence you need to make a judgement as to whether you value outright performance or developer friendliness.后一种方式可能会占用更多资源,但可能更容易理解和维护,因此您需要判断您是否重视彻底的性能或开发人员的友好性。 (For a query run once a day on a hundred employees you could argue that having the query be easier to understand would be better. For a query hitting tens of thousands of employees a second, performance should take precedence ) (对于每天对 100 名员工运行一次的查询,您可能会争辩说让查询更容易理解会更好。对于每秒访问数万员工的查询,性能应该优先)

Please use below query,请使用以下查询,

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM