从“GROUP BY”中选择“COUNT”

时间:2017-10-13 00:20:16

标签: sql tsql

我需要帮助解决这个问题。

有这个表:

CREATE TABLE Employees (
    Id int,
    Name varchar(30),
    Salary Money,
    BossId int,
    Ocupation varchar(20))

INSERT INTO Employees VALUES(1,'Juan',15000,7,'Ventas')
INSERT INTO Employees VALUES(2,'Federico',16000,7,'Ventas')
INSERT INTO Employees VALUES(3,'Marcos',12000,8,'Compras')
INSERT INTO Employees VALUES(4,'Alberto',9000,8,'Compras')
INSERT INTO Employees VALUES(5,'Gonzalo',5000,8,'Compras')
INSERT INTO Employees VALUES(6,'Noelia',13000,7,'Ventas')
INSERT INTO Employees VALUES(7,'Roberto',20000,9,'Ventas')
INSERT INTO Employees VALUES(8,'Diego',19000,9,'Ventas')
INSERT INTO Employees VALUES(9,'Damian',25000,null,'Compras')

如何获得超过两名员工的员工的姓名,工资和负责人数?

结果将是:

Roberto  2000   3 
Diego    19000  3

谢谢!

1 个答案:

答案 0 :(得分:0)

SELECT
    E1.Name
    , E1.Salary
    , COUNT(*) Employees
FROM
    Employees E1
    JOIN Employees E2 ON E1.Id = E2.BossId
GROUP BY
    E1.Name
    , E1.Salary
HAVING COUNT(*) > 2