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

时间:2011-07-11 04:28:44

标签: sql sql-server

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

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

RollNo      Name
    1       Yoko
    1       Yoko
    1       Yoko

我想获得第三张唱片。我如何识别这一独特记录?

2 个答案:

答案 0 :(得分:3)

任何行都是第三行: - )

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)

答案 1 :(得分:1)

您可以使用DISTINCT返回列的不同组合。

SELECT DISTINCT RollNo, Name
FROM mytable