Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择时如何忽略某些类似行_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 选择时如何忽略某些类似行

Sql 选择时如何忽略某些类似行,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有下表 Id col1 col2 col3 1 c 2 m 2 c 3 6 2 b d u 3 e 6 9 4 1 v 8 4 2 b t 4 4 5 g 如您所见,id列2和4中存在重复值。我只想选择具有唯一id值的行,并忽略以下具有重复id值的行。我只想用重复的值保留第一行 1 c 2 m 2 c 3 6 3

我有下表

Id  col1 col2 col3
1    c    2     m
2    c    3     6
2    b    d     u
3    e    6     9
4    1    v     8
4    2    b     t
4    4    5     g
如您所见,id列2和4中存在重复值。我只想选择具有唯一id值的行,并忽略以下具有重复id值的行。我只想用重复的值保留第一行

1    c    2     m
2    c    3     6
3    e    6     9
4    1    v     8
存在FK约束,因此无法删除具有重复值的行

我正在使用SQLServer2008R2


任何回复都将不胜感激。

您可以使用
行号
以相同的
id对每行进行编号。然后,您只能根据
id
选择第一行:

select  *
from    (
        select  row_number() over (partition by id order by col1, col2, col3) rn
        from    YourTable
        ) as SubQueryAlias
where   rn = 1

子查询是必需的,因为SQL Server不允许直接在
where
子句中使用
row\u number

如何确定要在结果中使用哪些重复行?是否存在保证唯一的字段组合,例如
Id,Col1
,以便将其用作键?