选择最大或最小结果

时间:2012-03-26 14:46:24

标签: sql oracle select max min

我的查询一直给我带来麻烦。我认为可能有一个简单的解决方案,但请尽可能帮助我!

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

顺便说一句,这是一个oracle DB。

有什么建议吗?

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','none@none.com')
AND table2.EMAIL like '%@%'

1 个答案:

答案 0 :(得分: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','none@none.com')
       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','none@none.com')
       AND table2.EMAIL like '%@%'