[英]SQL query to find SUM
I'm new too SQL and I've been struggling to write this query. 我也是SQL的新手,我一直在努力编写此查询。 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? 我想找到给定部门中雇员的所有薪资的总和,假设为“ M”,给定的雇用日期,假设为“ 2002”,有什么想法吗? 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. 这与HR模式在Oracle中的实现方式非常相似,因此我认为该模式应该可以,现在只需查询帮助即可。
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 ,
). FWIW,您不应该使用旧的ANSI-89 隐式连接表示法 (使用,
)。 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?). 自ANSI-92标准(超过20年前!)以来,它就被视为已弃用,并且一些供应商开始放弃其支持(MS SQL Server 2008;我不知道对于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
. 使用该语法, JOIN
关系( USING
或ON
)与过滤子句WHERE
之间有明显的区别。 It will later ease things when you will encounter "advanced" joins such as OUTER JOIN
. 当您遇到诸如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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.