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;
Advertisement
Answer
Code you posted wouldn’t compile; it lacks LAST_NAME
in the GROUP BY
(which is, basically, wrong as it would make what you’re doing impossible) or – a better idea – remove it from the SELECT
statement’s column list.
Using RANK
analytic function, you’d then have
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;
I don’t have your tables nor data so – for illustration – I’ll use Scott’s sample schema. Simplified, it would be like this:
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
So:
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>