💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
:-: ![](https://img.kancloud.cn/42/12/42122f743a2cda5a968ac02a6d8b3924_560x395.png) 如图中所示,`uid = 50222`的用户在`2022-11-22`这一天连续签到了10次。很明显此表没有**唯一索引**,但是代码方面的原因暂不考虑(不是咱写的) ![](https://img.kancloud.cn/92/1e/921edd252fbd306eee07c0400fb223a6_850x170.png) ### 要求: 删除重复数据,并且保留最新一条(用户一天重复有十条,删九留一) > PS:其实不难,由于没有接触过 **SQLServer**,还有其中涉及的几个函数,所以记录一下 ### 思路: 1. 查出所有重复签到的数据 2. 查出重复签到中最新的一条数据 3. 删除 ~~~ -- 统计重复数据 SELECT convert(varchar(10), addtime,20) time, uid, COUNT(uid) count FROM wap_qda GROUP BY convert(varchar(10), addtime,20), uid HAVING count(uid) > 1 -- 重复签到中最新的一条数据ID SELECT MAX(ID) ID FROM wap_qda GROUP BY convert(varchar(10), addtime,20), uid HAVING count(uid) > 1 -- 全部重复数据 SELECT a.* FROM wap_qda a, (SELECT convert(varchar(10), addtime,20) time, uid FROM wap_qda GROUP BY convert(varchar(10), addtime,20), uid HAVING count(uid) > 1) b WHERE convert(varchar(10), a.addtime,20) = b.time AND a.uid = b.uid -- 删除 DELETE FROM wap_qda WHERE wap_qda.ID IN (SELECT a.ID FROM wap_qda a, (SELECT convert(varchar(10), addtime,20) time, uid FROM wap_qda GROUP BY convert(varchar(10), addtime,20), uid HAVING count(uid) > 1) b WHERE convert(varchar(10), a.addtime,20) = b.time AND a.uid = b.uid) AND wap_qda.ID NOT IN (SELECT MAX(ID) ID FROM wap_qda GROUP BY convert(varchar(10), addtime,20), uid HAVING count(uid) > 1 ) ~~~ - **CONVERT()** [CONVERT()](https://www.w3school.com.cn/sql/func_convert.asp) 函数是把日期转换为新数据类型的通用函数 CONVERT(data_type(length),data_to_be_converted,style) *data\_type(length)* 规定目标数据类型(带有可选的长度)。*data\_to\_be\_converted*含有需要转换的值。*style*规定日期/时间的输出格式。