sql查询以升序获取输出

时间:2019-06-12 21:02:06

标签: sql oracle

我有一个包含以下各列的表格:薪金和部门

这些是表的内容:

IT      600000

HR      530000

IT     1000000

HR      480000

Payroll 500000

我想编写一个查询来获取部门,每个部门的薪资总额并按薪资总额的升序对其进行排序。

这是我尝试过的查询:

select Department, salary,
sum(Salary)
from table 
order by Department DESC;

但是我得到的输出为:

Payroll 500000 3110000

我需要获得显示每个部门总和的输出。

2 个答案:

答案 0 :(得分:1)

方法如下:

SQL> with test (department, salary) as
  2    (select 'IT'     ,  600000 from dual union all
  3     select 'HR'     ,  530000 from dual union all
  4     select 'IT'     , 1000000 from dual union all
  5     select 'HR'     ,  480000 from dual union all
  6     select 'Payroll',  500000 from dual
  7    )
  8  select department, sum(salary) sum_sal
  9  from test
 10  group by department
 11  order by sum_sal;

DEPARTM    SUM_SAL
------- ----------
Payroll     500000
HR         1010000
IT         1600000

SQL>

查询中包含的薪水列在此情况下为错误,因为您还必须按薪水分组,因此您将获得源表本身。

答案 1 :(得分:0)

然后使用group by Department

select Department, sum(Salary) as salary
  from "table" 
 group by Department
 order by salary
  • table是oracle的保留关键字,因此我用引号引起来
  • 未聚合的salary列应从选择列表中删除