如何在SQL Server中的多行上应用非重复?我在下面尝试过的查询在SQL Server上不起作用。
select distinct(column1, column2), column3
from table_name
答案 0 :(得分:1)
select distinct
适用于该行中的所有列。因此,您可以这样做:
select distinct col1, col2, col3
from t;
如果您只想让col1
和col2
不同,那么group by
可以起作用:
select col1, col2, min(col3)
from t
group by col1, col2;
或者,如果要随机行,则可以使用row_number()
。例如:
select t.*
from (select t.*,
row_number() over (partition by col1, col2 order by newid()) as seqnum
from t
) t
where seqnum = 1;
一个聪明的版本不需要子查询:
select top (1) with ties t.*
from t
order by row_number() over (partition by col1, col2 order by newid());