SQL 列出所有重複的資料
情境說明
假設有一個員工的資料表 #Employee,其中有一個欄位 EmpName 記錄著員工的姓名,我們希望能夠查出在這張表內有哪些人的姓名是相同的,如下圖數據,我們期望可以找出 2 筆 Lawrence,有底下幾種常見的寫法。
- 若只是單純想找出,不重複的 EmpName,直接 Distinct 即可。
Select Distinct EmpName From #Employee - 使用 Group By 來找出 EmpName 超過一筆以上的資料,並顯示實際的資料筆數。
Select EmpName, Count(EmpName) as RecordCount From #Employee Group By EmpName Having count(EmpName) > 1 - 查出單位內所有重複姓名的人完整資料表數據
Select * From #Employee Where EmpName in (Select EmpName From #Employee Group By EmpName Having count(EmpName) > 1 ) -- or Select * From #Employee main Where (Select Count(EmpName) From #Employee sub where main.EmpName = sub.EmpName ) >1
建立本文範例資料表
相關語法如下參考,使用完畢記得刪除不要的測試資料表喔。
-- 建立測試資料表 CREATE TABLE #Employee ( EmpNo varchar(10), EmpName nvarchar(20)) -- 建立測試資料 Insert Into #Employee values('001', N'Lawrence') Insert Into #Employee values('002', N'Olivier') Insert Into #Employee values('003', N'Lawrence') Insert Into #Employee values('004', N'Lawrence Shen') Insert Into #Employee values('005', N'John') Insert Into #Employee values('006', N'Amber') Insert Into #Employee values('007', N'Joyce') Insert Into #Employee values('008', N'Lawrence') Insert Into #Employee values('009', N'Lawrence Shen') -- 刪除測試資料表 Drop Table #Employee
明天我會記錄一下,另外一個常見的情境,找出最高學歷的問題。
留言
張貼留言
您好,我是 Lawrence,這裡是我的開發筆記的網誌,如果你對我的文章有任何疑問或者有錯誤的話,歡迎留言讓我知道。