简体   繁体   中英

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. Desired result:

amount  employee 
300            a 
1200         rest 

Use a case expression for the group by key:

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. (This happens to use MySQL, but this is standard SQL and will work in any database.)

Convert the employee values using CASE WHEN and group the converted value:

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:

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 )

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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