SQL:通过"应用"组查询,附加逻辑

时间:2017-04-18 22:28:33

标签: mysql sql database

给定一个带有字段的员工表" DeptId"和" employeeId",如何显示所有员工多于部门20的部门? 我想在部门中显示部门ID和员工人数。

到目前为止,我已经尝试过了:

SELECT DeptId as "Dept Id", count(employeeId) as "Number of employee"
FROM EMPLOYEE 
WHERE DeptId IN
 (
   SELECT DeptId
    FROM EMPLOYEE
   GROUP BY DeptId
  )
AND DeptId <> 20
group by DeptId;

我似乎无法解决我需要找到员工人数超过20人的部门。

P.S Total newb

2 个答案:

答案 0 :(得分:1)

为了便于解释,假设您有以下#Employee表:

+ ------ + -------------------- + ------- +
| Emp_Id | Emp_Name             | Dept_Id |
+ ------ + -------------------- + ------- +
| 1      | Jim Ralston          | 6       |
| 2      | Dave Davidson        | 20      |
| 3      | Alexander The Great  | 18      |
| 4      | Tribbidy Trump       | 12      |
| 5      | Anglo Saxon          | 6       |
| 6      | Henry Ford           | 2       |
| 7      | Thomas Eddison       | 9       |
| 8      | Running out of names | 4       |
| 9      | Two More             | 4       |
| 10     | Done!                | 4       |
+ ------ + -------------------- + ------- +

按Dept_Id分组并添加一个having子句,指定计数应大于部门20的计数:

select Dept_Id, COUNT(*) as NumberOfEmployees
    from #Employee
    group by Dept_Id
    having COUNT(*) > (
        select COUNT(*)
            from #Employee
            where Dept_Id = 20
    )

给我们这张表:

+ ------- + ----------------- +
| Dept_id | NumberOfEmployees |
+ ------- + ----------------- +
| 4       | 3                 |
| 6       | 2                 |
+ ------- + ----------------- +

答案 1 :(得分:-1)

您需要额外的逻辑(另一个“AND”)。而不是“WHERE”子句(在“GROUP BY”之前运行),您需要a "HAVING" clause,它在“GROUP BY”之后运行。您的附加逻辑可以包括子查询以查找部门20的大小。将该结果与每个部门的大小进行比较。

create or replace TRIGGER MAJ_PRIX_COMMANDE
AFTER INSERT OR UPDATE OR DELETE ON REGROUPE
FOR EACH ROW
DECLARE 
resultat NUMBER; 
BEGIN
UPDATE COMMANDE
SET COMMANDE.prixTotal = multiplicateur((CAST((SELECT SUM(prixRegroupe)FROM REGROUPE WHERE REGROUPE.numCommande = :NEW.numCommande)AS NUMBER)),1.15,resultat)

WHERE COMMANDE.numCommande = :NEW.numCommande;
END;