在Oracle中选择DISTINCT或UNIQUE记录或行

时间:2012-06-25 17:06:08

标签: sql unique distinct

我想从我查询的数据库中选择不同或唯一的记录。我怎么能这样做,但同时选择整个记录而不仅仅是我区分为独特的列?我必须做不守规矩的连接吗?

3 个答案:

答案 0 :(得分:5)

根据您使用的数据库,您可以使用窗口功能。如果您只想要从不重复的行:

select t.*
from (select t.*,
             count(*) over (partition by <id>) as numdups
      from t
     ) t
where numdups = 1

如果您想要每行的一个示例:

select t.*
from (select t.*,
             row_number(*) over (partition by <id> order by <id>) as seqnum
      from t
     ) t
where seqnum = 1

如果你没有窗口功能,你可以通过“unruly join”完成同样的事情。

答案 1 :(得分:3)

如果您只希望其中一列中的一列是唯一的,并且您有可能包含多条记录的联接,则必须确定您希望查询提供的两个或更多值中的哪一个。这可以通过聚合函数,相关子查询或派生表或CTE来完成(在SQL Server中不确定Oracle是否具有这些)。

但是在编写查询之前,您必须确定所需的值。一旦你知道那么你可能知道如何得到它。

以下是一些快速示例(我使用了SQL Server编码约定,但大部分内容在Oracle中都有用,因为它是所有基本SQL,Oracle可能有不同的方式来声明参数):

select a.a_id, max (b.test) , min (c.test2)
from tablea a 
join tableb b on a.a_id = b.a_id
join tablec c on a.a_id = c.a_id
group by a.a_id
order by b.test, c.test2

Select a.a_id, (select top 1 b.test from tableb b where a.a_id = b.a_id order by test2),
(select top 1 b.test2 from tableb b where a.a_id = b.a_id order by test2),
(select top 1 c.test3 from tablec c where a.a_id = c.a_id order by test4)
from tablea a   

declare @a_id int
set @a_id = 189
select a.a_id , b.test, b.test4
from tablea a 
join tableb b on a.a_id = b.a_id
join (select min(b.b_id) from tableb b where b.a_id = @a_id order by b.test3) c on c.b_id = b.b_id
where a.a_id = @a_id

答案 2 :(得分:0)

在第二个例子中


  select t.*
from (select t.*,
             row_number() over (partition by id order by id ) as seqnum
      from t
     ) t
where seqnum = 1

行括号中的row_number()必须没有星号。