SQL TOP 1在子查询中使用时返回null

时间:2018-06-04 12:06:52

标签: sql sql-server greatest-n-per-group

请帮助解决这个子查询 - 它可以正常运行一个客户端,但在添加到查询时返回null。

对于每个客户,我需要获得订单最多的员工。

这是一个更大的查询的一部分,因此性能也是一个问题。

SELECT c.ClientId, s.BestEmployeeId 
FROM client c
LEFT OUTER JOIN(
SELECT TOP 1 o.EmployeeId AS BestEmployeeId, count(o.EmployeeId) AS cnt, o.ClientId
    FROM Orders o
    WHERE o.EmployeeId > 0
    AND o.EmployeeId is not null    
    GROUP BY o.ClientId, o.EmployeeId
    ORDER BY cnt DESC
) AS s on c.ClientId = s.ClientId

2 个答案:

答案 0 :(得分:2)

  

对于每个客户,我需要获得订单最多的员工。

我会使用聚合和窗口函数来执行此操作:

select oc.*
from (select o.client, o.employeeid, count(*) as cnt,
             rank() over (partition by o.client order by count(*) desc) as seqnum
      from Orders o
      group by o.client, o.employeeid
     ) oc
where seqnum = 1;

请注意,您似乎不需要client表,因为orders似乎同时包含clientemployeeid

您的版本正在过滤NULL employeeid的值。您也可以在子查询中执行此操作(尽管您的问题陈述没有说明此类值)。

答案 1 :(得分:0)

您可以apply使用

SELECT c.ClientId, b.BestEmployeeId 
FROM client c OUTER APPLY (
       SELECT TOP 1 o.EmployeeId AS BestEmployeeId
       FROM Orders o
       WHERE o.ClientId = c.ClientId AND o.EmployeeId > 0
       GROUP BY o.EmployeeId
       ORDER BY count(o.EmployeeId) DESC
   ) b;