是否可以将 TOP N WITH TIES 与 Union 一起使用?

问题描述 投票:0回答:1

我试图在他们各自的表中找到任务最多的管家和向导,我试图用联合来显示一个结果,但我收到这个错误:

“如果没有相应的 ORDER BY 子句,则不允许使用 TOP N WITH TIES 子句。”

SELECT TOP 1 with ties e.EmpID as 'EmployeeID', Count(ScheduleID) as 'Task Count'
FROM EMPLOYEE e, CLEANING c
where e.empid = c.hkid
group by e.empid
UNION
SELECT TOP 1 with ties e.EmpID as 'EmployeeID', Count(ResID) as 'Task Count'
FROM EMPLOYEE e, RESERVATION r
where e.empid = r.guideid
group by e.empid
order by 'Task Count' desc
sql sql-server union greatest-n-per-group
1个回答
0
投票

试试这个:

SELECT *
FROM
(
    SELECT TOP 1 with ties e.EmpID as 'EmployeeID', Count(ScheduleID) as 'Task Count'
    FROM EMPLOYEE e, CLEANING c
    where e.empid = c.hkid
    group by e.empid
    order by [Task Count] desc
)  DS
UNION
SELECT *
FROM
(
    SELECT TOP 1 with ties e.EmpID as 'EmployeeID', Count(ResID) as 'Task Count'
    FROM EMPLOYEE e, RESERVATION r
    where e.empid = r.guideid
    group by e.empid
    order by [Task Count] desc
) DS

或这个:

SELECT SELECT TOP 1 with ties EmployeeID, [Task Count]
FROM
(
    SELECT e.EmpID as 'EmployeeID', Count(ScheduleID) as 'Task Count'
    FROM EMPLOYEE e, CLEANING c
    where e.empid = c.hkid
    group by e.empid
    UNION
    SELECT ties e.EmpID as 'EmployeeID', Count(ResID) as 'Task Count'
    FROM EMPLOYEE e, RESERVATION r
    where e.empid = r.guideid
    group by e.empid
    
) DS
order by [Task Count] desc
© www.soinside.com 2019 - 2024. All rights reserved.