2012-03-26 83 views
0

我有一个查询,一直给我麻烦。我认为可能有一个简单的解决方案,但请尽可能帮助我!选择最大或最小结果

我的主要问题是,通常每个cust_id有多个电子邮件。有唯一的标识符,如序列号(seq_no)和更新日期(updated_date)。我只想要为任何一个客户展示最新的电子邮件地址。

顺便说一下,这是一个oracle数据库。

有什么建议吗?

SELECT DISTINCT 
table1.indident_id, 
table1.incident_detail_id, 
table1.incdent_entered_date, 
table1.entering_employee, 
table2.EMAIL 
FROM table1 
left outer join table2 on table1.cust_id=table2.cust_id 
WHERE table1.incdent_entered_date>=current_date-4 
AND table1.table1.incident_detail_id=(select min(table1.table1.incident_detail_id)from table1) 
AND table2.EMAIL NOT IN ('NONE','none','[email protected]') 
AND table2.EMAIL like '%@%' 
+0

可能的复制HTTP做什么:// stackoverflow.com/questions/2631230/how-to-select-the-record-contains-maxsome-field-within-groupgroup-by – 2012-03-26 15:09:10

回答

0

有几个选项。最有效的是使用分析功能。

SELECT * 
    FROM (
    SELECT table1.indident_id, 
      table1.incident_detail_id, 
      table1.incdent_entered_date, 
      table1.entering_employee, 
      table2.EMAIL, 
      row_number() over (partition by table2.cust_id 
            order by table2.updated_date desc) rnk 
     FROM table1 
      left outer join table2 on table1.cust_id=table2.cust_id 
    WHERE table1.incdent_entered_date>=current_date-4 
     AND table1.table1.incident_detail_id=(select min(table1.table1.incident_detail_id) 
               from table1) 
     AND table2.EMAIL NOT IN ('NONE','none','[email protected]') 
     AND table2.EMAIL like '%@%' 
) 
WHERE rnk = 1 

效率较低,但东西,将工作在几乎任何数据库,将做类似的东西你目前与incident_detail_id子查询

SELECT table1.indident_id, 
      table1.incident_detail_id, 
      table1.incdent_entered_date, 
      table1.entering_employee, 
      table2.EMAIL 
     FROM table1 
      left outer join table2 on table1.cust_id=table2.cust_id 
    WHERE table1.incdent_entered_date>=current_date-4 
     AND table1.table1.incident_detail_id=(select min(table1.table1.incident_detail_id) 
               from table1) 
     AND table2.update_date = (SELECT MAX(t2_inner.update_date) 
            FROM table2 t2_inner 
            WHERE t2_inner.cust_id = table1.cust_id) 
     AND table2.EMAIL NOT IN ('NONE','none','[email protected]') 
     AND table2.EMAIL like '%@%' 
+0

谢谢。这真的帮了我。 – NewbBill 2012-03-26 16:31:52