在我的数据库中,有来自同一员工的多个条目,因此我希望通过识别自动编号字段来获取最新条目。但是在eno中使用下面带有distinct的sql代码会导致重复的条目。
SELECT distinct(eNo), auto_num from mc_employee
order by auto_num
关于我做错了什么的线索?
答案 0 :(得分:5)
DISTINCT
未应用于SELECT
子句的特定字段。它更适用于所有 SELECT
子句中的字段。
如果您想获得最新记录,可以使用ROW_NUMBER
:
SELECT eNo, auto_num
FROM (
SELECT eNo, auto_num,
ROW_NUMBER() OVER (PARTITION BY eNo ORDER BY auto_num DESC) AS rn
from mc_employee ) AS t
WHERE t.rn = 1
ORDER BY auto_num
答案 1 :(得分:1)
尝试以下查询:
SELECT eNo,auto_num
FROM
( SELECT eNo, auto_num, ROW_NUMBER() OVER(PARTITION BY eNo ORDER BY auto_num DESC) as RN
FROM mc_employee
)T
WHERE RN=1
答案 2 :(得分:0)
最简单的方法是TOP(1) WITH TIES ... ORDER BY ROW_NUMBER() OVER ()
SELECT TOP(1) WITH TIES eNo, auto_num
FROM mc_employee
ORDER BY ROW_NUMBER() OVER (PARTITION BY eNo ORDER BY auto_num DESC)
答案 3 :(得分:0)
这也是一个子选择解决方案:
SELECT distinct(dist.eNo), (select max(auto_num) from mc_employee i where i.eNo=dist.eNo) auto_num
from mc_employee dist
order by auto_num