【问题标题】:I'm trying to know the country that pays the highest salary from我想知道工资最高的国家
【发布时间】:2020-01-31 11:14:43
【问题描述】:
select last_name, country_name, SUM(salary)
from employees e JOIN departments d ON (e.department_id= d.department_id) 
JOIN locations L ON (d.location_id = L.location_id) 
JOIN Countries Cc ON (L.country_id = Cc.country_id) 
JOIN regions Rr ON (Cc.region_id = Rr.region_id) 
GROUP BY country_name;

【问题讨论】:

  • 编辑问题添加一些示例数据和所需的结果会有所帮助。

标签: sql oracle11g oracle-sqldeveloper


【解决方案1】:

您发布的代码无法编译;它在GROUP BY 中缺少LAST_NAME(这基本上是错误的,因为它会使您正在做的事情不可能)或者- 一个更好的主意- 从SELECT 语句的列中删除它列表。

使用RANK 解析函数,您将拥有

WITH data
     AS (  SELECT country_name,
                  SUM (salary) sumsal,
                  RANK () OVER (ORDER BY SUM (salary) DESC) rn
             FROM employees e
                  JOIN departments d ON (e.department_id = d.department_id)
                  JOIN locations L ON (d.location_id = L.location_id)
                  JOIN Countries Cc ON (L.country_id = Cc.country_id)
                  JOIN regions Rr ON (Cc.region_id = Rr.region_id)
         GROUP BY country_name)
SELECT country_name, sumsal
  FROM data
 WHERE rn = 1;

我没有您的表格或数据,所以——为了说明——我将使用 Scott 的示例模式。简而言之,应该是这样的:

SQL> select deptno, sum(sal)
  2  from emp
  3  group by deptno
  4  order by 2 desc;

    DEPTNO   SUM(SAL)
---------- ----------
        10      13750        --> this is a department you need
        20      10995
        30       9400

所以:

SQL> WITH data
  2       AS (  SELECT deptno,
  3                    SUM (sal) sumsal,
  4                    RANK () OVER (ORDER BY SUM (sal) DESC) rn
  5               FROM emp
  6           GROUP BY deptno)
  7  SELECT deptno, sumsal
  8    FROM data
  9   WHERE rn = 1;

    DEPTNO     SUMSAL
---------- ----------
        10      13750

SQL>

【讨论】:

    【解决方案2】:

    您只想显示中间结果的最佳行。从 Oracle 12c 开始,您可以为此使用 FETCH FIRST n ROWS 子句。在 Oracle 11g 之前,您应该改用窗口函数:

    SELECT country_name, sum_salary
    FROM
    (
      select 
        c.country_name,
        SUM(e.salary) AS sum_salary,
        MAX(SUM(e.salary)) OVER () AS max_sum_salary
      from employees e 
      JOIN departments d ON e.department_id = d.department_id
      JOIN locations l ON d.location_id = l.location_id
      JOIN countries c ON l.country_id = c.country_id
      GROUP BY c.country_name
    )
    WHERE sum_salary = max_sum_salary
    ORDER BY country_name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2019-11-10
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多