Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking the record with the max date

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 of A). I could write

SELECT A, col_date   FROM TABLENAME t_ext  WHERE col_date = (SELECT MAX (col_date)                      FROM TABLENAME t_in                     WHERE t_in.A = t_ext.A) 

But my query is really long... is there a more compact way using ANALYTIC FUNCTION to do the same?

like image 733
Revious Avatar asked Jan 17 '12 16:01

Revious


People also ask

How do I find the record with the max date?

Select row with max date per user using MAX() function Another way to get the latest record per user is using inner queries and Max() function. Max() function, when applied on a column, gives the maximum value of that column.

Can I use Max on date in SQL?

Unfortunately, you cannot use the max(date) function with the where clause. Doing so will result in an error as shown: select * from employees where max(start_date); This is because SQL does not allow aggregate functions in the where clause.

Can we use Max on date?

MAX() function will give you the maximum values from all the values in a column. MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.


2 Answers

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.

like image 86
Justin Cave Avatar answered Oct 14 '22 06:10

Justin Cave


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 GROUP BY A ) SELECT t.A, t.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 
like image 23
Benoit Avatar answered Oct 14 '22 06:10

Benoit