简体   繁体   中英

SQL query to find SUM

I'm new too SQL and I've been struggling to write this query. I want to find the SUM of all salaries for employees in a give department, let's say 'M', and a given hire date, let's say '2002', any ideas? I'm thinking I have to JOIN the tables somehow but having trouble, I've set up a schema like this.

jobs table and columns

JOBS
------------
job_id
salary
hire_date

employees table and columns

EMPLOYEES
------------
employee_id
name
job_id
department_id

department table and columns

DEPARTMENTS
------------
department_id
department_name

This is very similar to the way the HR schema does it in Oracle so I think the schema should be OK just need help with the query now.

You need a statement like this:

    SELECT e.name, 
           d.department_name, 
           SUM(j.salary)
      FROM employees e, 
           departments d, 
           jobs j
     WHERE d.department_name = 'M' 
       AND TO_CHAR(j.hire_date, 'YYYY') = '2002'
       AND d.department_id = e.department_id 
       AND e.job_id = j.job_id
  GROUP BY e.name, 
           d.department_name;

FWIW, you shouldn't use the old ANSI-89 implicit join notation (using , ). It is considered as deprecated since the ANSI-92 standard (more than 20 yers ago!) and some vendors start dropping its support (MS SQL Server 2008; I don't know if there is a deprecation warning for this "feature" with Oracle?).

So, as a newcomer, you shouldn't learn bad habits from the start.

With the "modern" syntax, your query should be written:

SELECT e.name, 
       d.department_name, 
       SUM(j.salary)
  FROM employees e
  JOIN departments d USING(department_id)
  JOIN jobs j USING(job_id)

 WHERE d.department_name = 'M' 
   AND TO_CHAR(j.hire_date, 'YYYY') = '2002'

 GROUP BY e.name, d.department_name;

With that syntax, there is a clear distinction between the JOIN relation ( USING or ON ) and the filter clause WHERE . It will later ease things when you will encounter "advanced" joins such as OUTER JOIN .

Yes, you just need a simple inner JOIN between all three tables.

SELECT SUM(salary)
FROM JOBS j
JOIN EMPLOYEES e ON j.job_id = e.job_id
JOIN DEPARTMENTS d ON e.department_id = d.department_id
WHERE d.department_name = 'M'
AND e.hire_date = 2002

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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