SQL中怎麼去除重複的號碼,並且保留最早填寫的

個人信息表的重複號碼

個人信息表 info:
在這裏插入圖片描述
唯一主鍵註冊人員編號 no,註冊日期 ctime,以及手機號碼 phone_num。由於一個註冊人 只能有一個註冊手機號碼,系統中手機號存在重複,屬於系統 bug。
(1)、找出重複的手機號碼,以及對應的註冊人信息;

select * from info;

select phone_num,count(phone_num) from info group by phone_num;

select phone_num,count(phone_num) from info group by phone_num having count(phone_num)>1;

select phone_num from info group by phone_num having count(phone_num)>1;

select * from info where phone_num in (select phone_num from info group by phone_num having count(phone_num)>1);

(2)、將重複手機號碼的記錄刪除,重複的記錄中,保留最早註冊時間的記錄

開窗函數row_number()的基本語法爲

row_number() over (partition by column1, column2 order by column3 desc) as new_name

該函數的作用是,按照column1和column2對數據進行分組,在每一個分組內,按照column3進行排序,排序之後,對每一個分組內的多行數據,標記上序號,序號從1開始,依次遞增。當然,可以給序號取一個新的名字new_name。

進行開窗操作後,就可以再進行一次select+where操作,來選出需要的數據了。


SELECT  a.`no`,a.ctime,a.phone_num FROM (SELECT `no`,phone_num,ctime ,row_number() over(partition by phone_num order by ctime asc) r where a.r = 1;

用的是mysql的話可能需要mysql5.8才能操作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章