Taking the record with the max date

前端 未结 6 1978
忘了有多久
忘了有多久 2020-12-08 10:05

Let\'s assume I extract some set of data.

i.e.

SELECT A, date
FROM table

I want just the record with the max date (for each value o

相关标签:
6条回答
  • 2020-12-08 10:28

    Justin Cave answer is the best, but if you want antoher option, try this:

    select A,col_date
    from (select A,col_date
        from tablename 
          order by col_date desc)
          where rownum<2
    
    0 讨论(0)
  • 2020-12-08 10:33

    You could also use:

    SELECT t.*
      FROM 
            TABLENAME t
        JOIN
            ( SELECT A, MAX(col_date) AS col_date
              FROM TABLENAME
              GROUP BY A
            ) m
          ON  m.A = t.A
          AND m.col_date = t.col_date
    
    0 讨论(0)
  • 2020-12-08 10:34

    If date and col_date are the same columns you should simply do:

    SELECT A, MAX(date) FROM t GROUP BY A
    

    Why not use:

    WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
    SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date
    

    Otherwise:

    SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
      FROM TABLENAME
     GROUP BY A
    
    0 讨论(0)
  • 2020-12-08 10:40

    A is the key, max(date) is the value, we might simplify the query as below:

    SELECT distinct A, max(date) over (partition by A)
      FROM TABLENAME
    
    0 讨论(0)
  • 2020-12-08 10:44

    The analytic function approach would look something like

    SELECT a, some_date_column
      FROM (SELECT a,
                   some_date_column,
                   rank() over (partition by a order by some_date_column desc) rnk
              FROM tablename)
     WHERE rnk = 1
    

    Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the ROW_NUMBER or the DENSE_RANK analytic function rather than RANK.

    0 讨论(0)
  • 2020-12-08 10:46
    SELECT mu_file, mudate
      FROM flightdata t_ext
     WHERE mudate = (SELECT MAX (mudate)
                         FROM flightdata where mudate < sysdate)
    
    0 讨论(0)
提交回复
热议问题