2012-03-26 82 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