Oracle在值之后选择最大记录

时间:2015-02-10 08:13:22

标签: sql oracle max

我有这样的桌子。我必须找到no ='000000001 001'和status = 6的最大日期(max_date_6)。 status = 1的日期(max_date_1),该日期在max_date_6之后。我写了这样的查询,但它只给出了两种状态的最大值。但max_date_6必须为20943,max_date_1必须为21002

WITH max_date_6 AS
(
         SELECT   no,
                  Max(DATE) date_6
         FROM     TABLE
         where    status=6
         AND      no='00000001   001'
         GROUP BY no ), max_date_1 AS
(
         SELECT   no,
                  max(DATE) date_1
         FROM     TABLE
         WHERE    status=1
         AND      no='00000001   001'
         GROUP BY no)
SELECT date_6,
       date_1
FROM   max_date_6,
       max_date_1 where date_6<=date_1

enter image description here

3 个答案:

答案 0 :(得分:0)

这里不需要复杂化,只需要两个MAX&#39; s

SELECT Max(case when status = 6 then DATE end) as date_6,
       Max(case when status = 1 then DATE end) as date_1
FROM   TABLE
where  no='00000001   001'

已编辑的版本,现在需要date_1&gt; max(date_6),如果没有date_1&gt;,则返回null。 max(date_6),否则与之前的结果相同。

SELECT Max(case when status = 6 then DATE end) as date_6,
       (select Max(DATE)
        from TABLE
        where status = 1
          and no = t1.no
          and date > (select max(date) from TABLE
                      where no = t1.no
                        and status = 6)) as date_1
FROM   TABLE t1
where  no = '00000001   001'

答案 1 :(得分:0)

因此,您需要date的最大status=6和{<1}}来自之前行的date。 除非你有一些收集行的顺序,否则这是不可能的。出于这个原因,我添加了列ID(也许你有一些其他键,但隐藏它)。 所以输入数据是:

status=1

查询和结果:

NO                TDATE STATUS ID
----------------- ----- ------ --
00000001   001    21223      1  1
00000001   001    21041      1  2
00000001   001    21002      1  3
00000001   001    20943      6  4
00000001   001    20939      6  5
00000001   001    20933      1  6
00000001   001    20943      6  7

答案 2 :(得分:0)

鉴于您的预期数据,听起来好像您希望状态= 1的最小日期,其中该日期大于状态= 6的最大日期。

WITH m6 AS (
     SELECT max(tdate) AS max_date_6
       FROM mytable
      WHERE status = 6
        AND no = '00000001   001'
)
SELECT min(m1.tdate) AS max_date_1, m6.max_date_6
  FROM mytable m1, m6
 WHERE m1.status = 1
   AND m1.no = '00000001   001'
   AND m1.tdate > m6.max_date_6;

可替换地:

WITH m6 AS (
     SELECT no, max(tdate) AS max_date_6
       FROM mytable
      WHERE status = 6
      GROUP BY no
)
SELECT min(m1.tdate) AS max_date_1, m6.max_date_6
  FROM mytable m1 INNER JOIN m6
    ON m1.no = m6.no
   AND m1.tdate > m6.max_date_6
 WHERE m1.status = 1
   AND m1.no = '00000001   001';