SQL查询使用子查询

时间:2016-10-26 06:50:31

标签: sql sql-server

Department (dNumber, dName)

Employee (SSN, eName, salary, /dNumber/)

Project (pNumber, pName, pLocation)

WorksOn (/SSN/, /pNumber/, hours)

这些是我正在使用的表格。我想列出超过5名员工工作的所有部门编号和名称,并计算工资超过40,000的员工人数。我想练习使用子查询。

这是我写的:

SELECT T.dNumber, T.dName, COUNT(T.SSN)
FROM 
(
SELECT d.dNumber, d.dName, e.SSN
FROM Department d, Employee e
WHERE e.salary > 40000 AND d.dNumber = e.dNo
) as T
GROUP BY dNumber, dName
HAVING COUNT(T.SSN) > 5;

但它看起来和感觉多余。这几乎就像我真的不需要使用子查询一样。有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为下面的查询会返回您预期的结果(对于MySql,如果是MSSQL,则需要将IF替换为CASE条件):

SELECT T.dNumber, T.dName, COUNT(T.SSN) AS TotalEmployees, sum(IF(T.salary > 4000, 1, 0)) AS EmployeesOverFourty
FROM Department d
INNER JOIN Employee e ON d.dNumber = e.dNo
GROUP BY dNumber, dName
HAVING TotalEmployees > 5;

答案 1 :(得分:0)


SELECT
    d1.dNumber,
    d1.dName,
    ISNULL (SUM (CASE WHEN e1.SSN IS NOT NULL THEN 1 ELSE 0 END), 0) AS EmployeeCount
FROM
(
    SELECT
        Department.dNumber,
        Department.dName
    FROM
        Employee
    JOIN
        Department
    ON
        Employee.dNumber = Department.dNumber
    GROUP BY
        Employee.dNumber
    HAVING
        COUNT(*) > 5
) AS d
LEFT JOIN
    Employee e1
ON
    e1.dNumber = d1.dNumber AND
    e1.Salary > 40000
GROUP BY
    d1.dNumber,
    d1.dName