SQL按某字段去重 保留按某个字段排序最大值

x33g5p2x  于2022-06-27 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(355)
select * from tablename as a
where not exists (
select 1 from tablename as b
 where b.name=a.name and b.id>a.id)

talename:要去重复的表

name:需要去重复的字段,可以有多个字段

ID:取id字段最大

例子:

create table tablename  (id int identity(1,1),attachid int,name varchar(10))
insert into tablename  values(23,'sss')
insert into tablename   values(33,'sdfs')
insert into tablename   values(33,'4434')
insert into tablename   values(45,'dsdsd')
 
select * from  tablename  as  a where not exists (select 1 from  tablename  where attachid=a.attachid and name<a.name)

按某个字段去重 保留按某个字段排序的最大/小值

​ 后面括号里的意思是再从原表中找有没有比当前记录相同字段的比较字段更大或更小的 如果有 则不插入 如果没有 则插入

​ exists 是个条件 后面的结果集有值的时候 条件成立 后面结果集为空的时候 条件不成立 所以后面子查询中select 后面跟什么字段不重要 关键是看结果集是否为空

​ 加not 是取相反的意思

​ name <a.name 是取最小的 反之是取最大的

原数据

id attachid name
1  23    sss
2  33    sdfs
3  33    4434
4  45    dsdsd

比较后

id     attachid  ``name
----------- ----------- ----------
1      23     sss
3      33     4434
4      45     dsdsd

注意:from后面不能跟别名只能跟临时表 #table

复杂一点的例子:

查询 WorkFlowTask 表中 ReceiveID为某值 而且状态是2或者3的 记录 而且在同样GroupID 中只保留时间最新的 并且结果按完成时间排序

(select * from 
( SELECT *,ROW_NUMBER() OVER(ORDER BY CompletedTime1 DESC) AS PagerAutoRowNumber
FROM WorkFlowTask 
WHERE ReceiveID='00000000-0000-0000-0000-000000009667' AND [Status] IN(2,3) ) as a 
where not exists  --其实后面只是一个查询条件(包含子查询)
        (select 1 from WorkFlowTask 
           where GroupID=a.GroupID and ReceiveTime>a.ReceiveTime and ReceiveID='00000000-0000-0000-0000-000000009667' AND [Status] IN(2,3)
         )

相关文章

微信公众号

最新文章

更多