Distinct In SQL 查询结果重复值
Distinct In SQL Query resulting duplicate Values
在我的数据库中有来自同一员工的多个条目,因此我想通过识别自动编号字段来获取最新条目。但是在 eno 中使用下面的 sql 代码和 distinct 会导致重复条目。
SELECT distinct(eNo), auto_num from mc_employee
order by auto_num
关于我做错了什么的任何线索?
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
尝试以下查询:
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
最简单的方法是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)
这里还有一个子select解决方案:
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
在我的数据库中有来自同一员工的多个条目,因此我想通过识别自动编号字段来获取最新条目。但是在 eno 中使用下面的 sql 代码和 distinct 会导致重复条目。
SELECT distinct(eNo), auto_num from mc_employee
order by auto_num
关于我做错了什么的任何线索?
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
尝试以下查询:
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
最简单的方法是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)
这里还有一个子select解决方案:
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