简体   繁体   中英

sum of column in sql server

I have an employee table in which there is a column of salary name. Now I want the sum of the salary column in the last row but the total should be written in the row next to it as per the photo below where null is written.

select emp_name,SUM(emp_salary) as salary 
from   employe 
group by emp_name WITH ROLLUP 
order by emp_name desc

在此处输入图像描述

And the table format looks the same with the employee name

You can use COALESCE :

coalesce(emp_name,'Total') as emp_name

In your query:

select coalesce(emp_name,'Total') as emp_name,
       SUM(emp_salary) as salary 
  from employe 
group by emp_name WITH ROLLUP 
order by emp_name desc

Here's another solution where the order is more explicit between the table rows and the total. It appears you want all the employee salary rows followed by the total at the bottom. Note: Popeye/Squirrel's answer is probably better in this specific case, but found this interesting anyway.

This might also be useful to someone wanting to output two sets of records and control the order of the groups and within each group.

Get the two (or more) groups of records to output and add a "hidden" Order field, which is used in the outer select to control the order of the groups.

;with salaries as (select '0' as [Order], emp_name, emp_salary from employe),
total as (select '1' as [Order], 'Total' as emp_name , SUM(emp_salary) as salary from employe)
select emp_name, emp_salary
from (
    select * from salaries
    union all
    select * from total
) a
order by [Order], emp_name desc

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