2

我正在使用 Oracle 10g。我在
SQL 上的研究 - 如何选择具有最大值

http://jan.kneschke.de/projects/mysql/groupwise-max/列的行

解决如何处理 max(row) 然后找到其他 max(rows) 但是,我还没有。

条件: ID 的 max(enroll_date) 代码必须为“WHEAT”。
我不想要代码为“WHEAT”的最长注册日期。仅当最大注册日期的代码为“WHEAT”时,我才需要该行。

问题:如何编写查询以满足条件?

这不起作用,因为它返回 ID=30, Code = WHEAT 其中 Date 12/25/2001 这不是该 ID 的最大(日期)。

    select ID, code, max(enroll_date)
    from enrollment
    where  CODE = 'WHEAT'
    group by ID, code

这也不起作用,因为它也返回 ID=30,代码 = WHEAT,其中日期 = 2001 年 12 月 25 日。

    select ID, code, max(enroll_date)
    from enrollment
    group by ID, code
    having code='WHEAT'

这是我的表

ENROLLMENT
===========================
ID  CODE     ENROLL_DATE
--------------------------
01  WHEAT   <NULL>
01  WHEAT   12/21/2007
01  WHEAT   7/30/2009
30  WHEAT   12/25/2001
30  CHAFF   6/14/2010
72  WHEAT   8/20/2002
72  WHEAT   12/7/2007

 DESIRED RESULT 
 ID    CODE ENROLL_DATE
 ================================
  01     WHEAT  7/30/2009
  72     WHEAT  12/7/2007
4

4 回答 4

7

听起来你想要类似的东西

SELECT id, 
       code,
       enroll_date
  FROM (SELECT id, 
               code,
               enroll_date,
               rank() over (partition by id 
                                order by enroll_date desc nulls last) rnk
          FROM enrollment)
 WHERE rnk = 1
   AND code = 'WHEAT'

分析函数为特定的值RANK分配最新的值 1,为该值分配下一个最近的值 2,等等。然后您可以参考外部查询中的排名和代码。如果可能有重复,您可能更喜欢使用or分析函数ENROLL_DATEIDENROLL_DATEIDDENSE_RANKROW_NUMBER

您也可以编写查询

SELECT id, 
       code,
       enroll_date
  FROM (SELECT id, 
               code,
               enroll_date,
               max(enroll_date) over (partition by id) max_enroll_date
          FROM enrollment)
 WHERE enroll_date = max_enroll_date
   AND code        = 'WHEAT'
于 2011-06-22T22:03:47.720 回答
2

Please look up "analytic functions" in the Oracle documentation -- this does what you want to do.

Basically, it lets you sort the records returned from the query in groups, but still give you access to all the columns from the row-- you just want to check that the first row in a group ordered by enroll_date has a code of 'WHEAT'

于 2011-06-22T21:48:16.633 回答
1

这个简单的查询会产生所需的结果

select * from t where enrolldate=
(select max(enrolldate) from t as t1
  where t.id=t1.id)
  and t.code='WHEAT'
于 2011-06-22T23:48:02.087 回答
1

出于查询的目的,您希望有一个单独的表,其中仅包含最大注册日期行。因此,您可以通过使用子查询来实现:

SELECT ID, Code, EnrollDate
FROM enrollment a
INNER JOIN (SELECT ID, MAX(EnrollDate) AS MaxEnrollDate
            FROM enrollment
            GROUP BY ID) b
ON (a.ID = b.ID AND a.EnrollDate = b.MaxEnrollDate)
WHERE Code = 'WHEAT'

希望我已经正确地做到了这一点。即使我没有,这个想法也应该奏效。

于 2011-06-22T22:04:43.333 回答