SQL Query Employees Database

I want to find a company that pays the lowest total salary and total salary.

Details are as follows:

works( empid, companyname, salary )

And my request looks like

SELECT COMPANYNAME 
FROM WORKS 
WHERE SALARY=
  (SELECT MIN(SUM(SALARY)) 
  FROM 
      (SELECT SUM(SALARY) 
      FROM WORKS 
      GROUP BY COMPANYNAME) 
GROUP BY COMPANYNAME);

but this does not return any rows.

I am new to SQL, so I hope you can answer me in an easily understandable way.

+4
source share
2 answers

, , works. total, , , , , . , .

, , , SQL- ( ). - , SQL, .

: , , ( , ) . GROUP BY, . , GROUPS ( ), HAVING, WHERE. - :

select   companyname, sum(salary) as total_salary
from     works
group by companyname 
having   sum(salary) = ( select   min(sum(salary))
                         from     works
                         group by companyname
                       )
;

, SQL - select min(sum(salary)) . ; , .

+2

Oracle 12c +:

SELECT COMPANYNAME, SUM(SALARY) 
FROM WORKS 
GROUP BY COMPANYNAME
ORDER BY SUM(SALARY)
FETCH FIRST 1 ROW ONLY;

ROW_NUMBER(), RANK() DENSE_RANK(). , , :

SELECT w.*
FROM (SELECT COMPANYNAME, SUM(SALARY) as total_salary,
             RANK() OVER (ORDER BY SUM(SALARY)) as seqnum
      FROM WORKS 
      GROUP BY COMPANYNAME
     ) w
WHERE seqnum = 1;

. ROW_NUMBER(), , .

+1

Source: https://habr.com/ru/post/1651877/


All Articles