如何通过ORACLE选择唯一记录

时间:2016-12-18 12:48:33

标签: sql oracle

当我执行“SELECT * FROM table”时,我得到如下结果:

 ID    Date         Time        Type
 ----------------------------------
 60    03/03/2013   8:55:00 AM   1                      
 60    03/03/2013   2:10:00 PM   2                                                  
 110   17/03/2013   9:15:00 AM   1                          
 67    24/03/2013   9:00:00 AM   1                          
 67    24/03/2013   3:05:00 PM   2

如您所见,每个ID在同一日期都有一个事务类型1和2 除了ID 110,只有Type 1

那么我怎么能得到这样的结果:

ID   Date        Time        Type
----------------------------------
110  17/03/2013  9:15:00 AM  1                          

因为第一个结果只返回一条记录

3 个答案:

答案 0 :(得分:2)

根据您的需要更改分区定义( import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; public class Employee { public static void main(String[] args) { LinkedList<Integer> ll=new LinkedList<>(); ArrayList<Integer> al=new ArrayList<>(); // Populating the LinkedList with sample Input ll.add(1); ll.add(2); ll.add(3); ll.add(3); ll.add(3); ll.add(3); ll.add(6); ll.add(null); //Searching the LinkedList for finding duplicates and then removing them for (int i = 0; i < ll.size(); i++) { for (int j = i+1; j <ll.size(); j++) { if(ll.get(i).equals(ll.get(j))) { al.add(ll.get(j)); } } } ll.removeAll(al); // Printing the LinkedList after removing duplicates for (Integer integer : ll) { System.out.println(integer); } } }

const QSet<QString> TOKEN = QSet<QString>::fromList(QStringList() << TK_IDENT << TK_DESK << TK_SPEC);

答案 1 :(得分:1)

您可以使用:

select * from my_table t
where exists (
select 1 from my_table
where id = t.id
group by id
having count(*) = 1
)

答案 2 :(得分:0)

如果只想输入类型1,则比较最小值和最大值。我更喜欢窗口功能:

select t.*
from (select t.*, min(type) over (partition by id) as mintype,
             max(type) over (partition by id) as maxtype
     from t
    ) t
where mintype = maxtype and mintype = 1;

如果您只想要相同类型的记录(而不是特定type = 1),请删除该条件。

如果您只想在同一天记录,请在partition by中添加日期。

在某些情况下,not exists可以更快:

select t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.type <> 1);