小编典典

如何从表的相同记录列表中获取一个唯一记录?表中没有唯一性约束

sql

我在SQL Server输出中有一个查询,

假设我有一个具有某些字段的表(Ex.StudentMaster)-没有唯一约束。对于前 RollNumber和Name该表具有相同的数据。例如:

RollNo      Name
    1       Yoko
    1       Yoko
    1       Yoko

我只想获得第三条记录。如何识别此唯一记录?


阅读 154

收藏
2021-04-07

共1个答案

小编典典

任何一行都是第三行:-)

create table test
(
n int,
name varchar(30)
);

insert into test values(1,'yoko'),(1,'yoko'),(1,'yoko');

select ROW_NUMBER() over(order by name) as ordinal, * from test;

删除“第三”行:-)

with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = 3

删除最后一行:

with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = (select MAX(ordinal) from a)
2021-04-07