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

标签 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

最佳答案

For each client I need to get the employee with the most orders.

我会用聚合和窗口函数来做到这一点:

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.

您的版本正在过滤掉 employeeidNULL 值。您也可以在子查询中执行此操作(尽管您的问题陈述未提及此类值)。

关于SQL TOP 1 在子查询中使用时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50680236/

相关文章:

MySQL:搜索从昨天下午 3 点到今天下午 4 点的订单

sql-server - 如何在 SQL Server Management Studio 2008 中自动执行 "generate scripts"任务?

mysql - 插入新值时使用同一 ID 中的数字插入另一个字段

sql - 如何在 SQL (postgres) 中按年份找到与最大资源相关的项目 ID?

python - SQLite:仅返回每个组中的前 2 个结果

sql - Mysql 内部查询不工作

sql - Gsql在构造查询时未执行

mysql - 加入mysql后如何按组/类别获取前n个解决方案?

mysql - 找不到列 : 1054 Unknown column - NO TYPOS NOR WRONG ' ` "

sql-server - Microsoft 可以将三值字段存储在一个位中吗?