在sql多列中选择group by

时间:2013-11-10 16:59:00

标签: sql select

我在一个表中有三列(代码,代码alt和产品)。代码列具有重复数据。我想在不重复代码列的情况下保留所有结果。我试着用这个

 Select code, code alt, product from table
 where code in 
  (
     select code from table
     group by code 
     having count (code)=1
     )

但不会出现所有结果。

由于

1 个答案:

答案 0 :(得分:0)

如果您只想使用具有相同代码的一堆行中的特定代码留下一行,则需要确定要从多行中选择哪一行。

您需要一些标准,通过这些标准,您可以使用相同的代码对行进行排名,并通过更高(例如)排名值从中选择一个。下面的脚本只留下一个 - 随机 - 行与特定代码。

这只是一个示例,向您展示了SQL Server的想法 - 因为您没有指出您的DBMS

with [src] as (
    select code, [code alt], product, rank() over(partition by code order by newid()) [rank]
    from [table])
select * from [src] where [rank] = 1

Ranking Functions

相关问题