Oracle SQL:使用多个条件只获取一个最大行

时间:2012-01-09 16:02:31

标签: sql oracle select

我有这张桌子:

Department   NAME   EMAIL         ID     DATE1         DATE2
1            John   asd@asd.com   74     05/04/2007    05/04/2007
1            Sam    asd@asd.com   23     05/04/2007    05/04/2007
1            Tom    asd@asd.com   46     05/04/2007    03/04/2007
1            Bob    bob@asd.com   23     01/01/2006
2            Tom    asd@asd.com   62     02/02/2000    05/05/1997

我想获得最多DATE1的行(每个部门只有一行),但它并不是唯一的!因此,如果有多个结果,我想获得最大DATE2,如果有多个,则返回ID最大的那个。

因此查询的结果将是:

1            John   asd@asd.com   74     05/04/2007    05/04/2007
2            Tom    asd@asd.com   62     02/02/2000    05/05/1997

非常感谢。

4 个答案:

答案 0 :(得分:18)

您需要使用ROW_NUMBER函数:

SELECT Department, NAME, EMAIL, ID, DATE1, DATE2
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY Department ORDER BY DATE1 DESC, DATE2 DESC, ID DESC) AS RowNumber, 
       Department, NAME, EMAIL, ID, DATE1, DATE2
FROM MyTable ) t
WHERE RowNumber = 1

答案 1 :(得分:5)

使用over子句:

select
    *
from
    (
    select
        Department,
        Name,
        Email,
        ID,
        DATE1,
        DATE2,
        max(DATE1) over (partition by Department) as MaxDate1,
        max(DATE2) over (partition by Department, DATE1) as MaxDate2,
        max(ID) over (partition by Department, DATE1, DATE2) as MaxID
    from
        employees
    ) x
where
    x.DATE1 = x.MaxDate1
    and x.DATE2 = x.MaxDate2
    and x.ID = x.MaxID

答案 2 :(得分:0)

像......那样的东西。

SELECT y2.*
FROM
(SELECT dept, 
  MAX(
    TO_CHAR(date1,'YYYYHH24MISS') || TO_CHAR(date2,'YYYYHH24MISS') 
    || id) as lastrec
 FROM yourtable y1
 GROUP BY dept) as ilv,
 yourtable y2
 WHERE y2.id=TO_NUMBER(SUBSTR(y2.lastrec, 21))

答案 3 :(得分:0)

SELECT
*
FROM
(
SELECT
    Department,
    Name,
    Email,
    ID,
    DATE1,
    DATE2,
    max(DATE1) over (partition by Department) as MaxDate1,
    max(DATE2) over (partition by Department, DATE1) as MaxDate2,
    max(ID) over (partition by Department, DATE1, DATE2) as MaxID
FROM
    employees
) 
WHERE
x.DATE1 = x.MaxDate1
AND x.DATE2 = x.MaxDate2
AND x.ID = x.MaxID