1

我想做这样的事情:

select
    EmployeeID e,
    SupervisorID s
from
    ReportingStructure
where
    count(select SupervisorID from ReportingStructure where EmployeeID = e) > 1

查找拥有多个主管的所有员工的员工 ID 和主管 ID。但我得到一个语法错误:

关键字“select”附近的语法不正确。

')' 附近的语法不正确。

我怎样才能得到这些数据?

4

4 回答 4

3

您可以使用以下命令将它们放在单独的行上exists

select EmployeeID, SupervisorID
from ReportingStructure rs
where exists (select 1   
              from ReportingStructure rs2
              where rs2.EmployeeID = rs.EmployeeID and
                    rs2.SupervisorID <> rs.SupervisorID
             );

如果您希望主管排成一排,您可以使用string_agg()

select EmployeeID, string_agg(SupervisorID, ',')
from ReportingStructure
group by EmployeeID
having count(*) = 2;
于 2020-04-23T19:52:05.980 回答
0

使用窗口函数作为

SELECT EmpId, COUNT(1) OVER(PARTITION BY EmpId) Cnt
FROM
(
    VALUES
    (1), (2), (2), (3), (3), (3)
) T(EmpId)

如果你想返回行,Cnt > 1那么

SELECT *
FROM
(
    SELECT EmpId, COUNT(1) OVER(PARTITION BY EmpId) Cnt
    FROM
    (
        VALUES
        (1), (2), (2), (3), (3), (3)
    ) T(EmpId)
) TT
WHERE Cnt > 1; 
于 2020-04-23T18:48:05.050 回答
0

似乎您最好使用这样的查询,因为这样您就没有 2 次扫描:

WITH CTE AS(
    SELECT EmployeeID AS e,
           SupervisorID AS s
           COUNT(EmployeeID) OVER (PARTITION BY EmployeeID) AS c
    FROM dbo.ReportingStructure)
SELECT e, s
FROM CTE
WHERE c > 1;
于 2020-04-23T18:44:41.200 回答
0

尝试有子句:

SELECT
    EmployeeID e,
    SupervisorID s
FROM
    ReportingStructure
HAVING COUNT(SupervisorID) > 1;
于 2020-04-23T18:47:50.837 回答