简体   繁体   English

是否存在使用SQL Server 2016的SQL查询以仅显示没有重复的记录?

[英]Is there SQL Query using SQL Server 2016 to display only record with no duplicates?

I have 我有

查询所有记录的结果

How to query so that the results will only display record having no duplicate without hard coding? 如何查询以便结果仅显示没有重复的记录而无需硬编码? See results 查看结果

使用硬编码查询结果

If you want empcode s with no duplicates, then one simple way uses aggregation: 如果您希望empcode没有重复项,那么一种简单的方法是使用聚合:

select empcode, min(leavecode) as leavecode
from t
group by empcode
having count(*) = 1;

This works, because if there is only one row for an empcode , then min(leavecode) is the leavecode . 这工作,因为如果只有一个用于排empcode ,然后min(leavecode) leavecode

An alternative method uses window functions: 另一种方法是使用窗口函数:

select empcode, leavecode
from (select t.*, count(*) over (partition by empcode) as cnt
      from t
     ) t
where cnt = 1;

Or, if leavecode s are unique when there are duplicates, perhaps the most efficient way: 或者,如果在存在重复项时leavecode是唯一的,则可能是最有效的方法:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.emp_code = t.empcode and t2.leavecode <> t.leavecode
                 );

You just select those records that have the empcode in a table of empcodes that only have one occurrence. 您只需在只有一次出现的empcodes表中选择那些具有empcode记录。

SELECT
  empcode,
  leavecode
FROM mytable
WHERE empcode in (
  SELECT empcode FROM mytable GROUP BY empcode HAVING count(1)=1
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM