SQL调节

时间:2017-09-08 04:21:37

标签: sql count

我想在澳大利亚境外展示部门名称和部门数量。

问题是,下面的代码仍然包含了澳大利亚各部门的统计数据。

(编辑) - 这更接近解决方案,但仍然不太正确。 - 没有返回正确的计数。

SELECT department_name, COUNT(COUNTRIES.country_id)
FROM DEPARTMENTS, COUNTRIES
JOIN (
     SELECT COUNT(COUNTRIES.country_name) AS COUNTRY
     FROM COUNTRIES
     JOIN DEPT_LOCATIONS ON COUNTRIES.country_id = DEPT_LOCATIONS.country_id
     WHERE country_name <> 'Australia'
     ) AS C ON COUNTRY = c.country
     GROUP BY department_name;

这是数据库架构:

COUNTRIES(country_id, country_name, region) 
• Primary key: {country_id}

DEPARTMENTS(department_id, department_name, manager_id)
• Primary key: {department_id }
• Foreign key: [manager_id]  ⊆ EMPLOYEES[employee_id]

DEPT_LOCATIONS(department_id, city, country_id)
• Primary key: {department_id, city}
• Foreign key: [department_id]  ⊆ DEPARTMENTS[department_id] and 
[country_id]  ⊆ COUNTRIES[country_id]

EMPLOYEES(employee_id, firstname, lastname, email, phone_no, salary, 
department_id)
• Primary key: {employee_id}
• Foreign key: [department_id]  ⊆ DEPARTMENTS[department_id]

2 个答案:

答案 0 :(得分:2)

你试过这个吗?

SELECT department_name, COUNT(DEPT_LOCATIONS.country_id)
FROM DEPARTMENTS
LEFT JOIN DEPT_LOCATIONS ON DEPARTMENTS.department_id = DEPT_LOCATIONS.department_id       
GROUP BY department_name
HAVING department_name <> 'Australia'

答案 1 :(得分:0)

弄清楚自己的欢呼声

SELECT department_name, COUNT(COUNTRIES.country_id)
FROM DEPARTMENTS, COUNTRIES
RIGHT JOIN DEPT_LOCATIONS ON DEPT_LOCATIONS.country_id = COUNTRIES.country_id
WHERE DEPARTMENTS.department_id = DEPT_LOCATIONS.department_id
AND country_name <> 'Australia'
GROUP BY department_name;