简体   繁体   English

sql 服务器中的列总和

[英]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.现在我想要最后一行中薪水列的总和,但总和应该写在它旁边的行中,如下图所示,其中 null 被写入。

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

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.这对于想要 output 两组记录并控制组和每个组内的顺序的人也可能有用。

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.将两组(或更多)记录获取到 output 并添加一个“隐藏”的Order字段,用于在外部 select 中控制组的顺序。

;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

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

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