2017-07-15 52 views
0

是否存在使用SQL Server 2016僅顯示沒有重複記錄的SQL查詢?

Query results for all records

如何查詢,以便有沒有硬編碼沒有重複的搜索結果只顯示記錄?看效果

Query Results using hardcode

+0

請分享你的表的細節和疑問:

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

或者,如果當有重複的,也許是最有效的方式leavecode s爲唯一您正在使用。 – ArunGeorge

+0

在你的例子中根本沒有重複的記錄 –

回答

2

你只選擇那些在empcodes的表只能有一個發生有empcode記錄。

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

非常感謝。它幫助我很多。 –

3

如果你想empcode s的沒有重複,那麼一個簡單的方法使用聚合:

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

這工作,因爲如果只有一行的empcode,然後min(leavecode)leavecode

另一種方法是使用窗口功能:

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

非常感謝。它有很多幫助。 –