Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DISTINCT BY MAX()?

Tags:

sql

mysql

How can I get the rows with the distinct TypeID with the maximum EffectivityDate?

Original Table

-----------------------------------------
| ID | TypeID | Value | EffectivityDate |
-----------------------------------------
|  1 |      1 |   2.3 |      1990-01-01 |
|  2 |      1 |   3.4 |      1999-10-31 |
|  3 |      2 |   1.1 |      1990-01-01 |
|  4 |      2 |   2.2 |      1999-10-31 |
|  5 |      3 |   6.1 |      1999-10-31 |
-----------------------------------------

Query Result

-----------------------------------------
| ID | TypeID | Value | EffectivityDate |
-----------------------------------------
|  2 |      1 |   3.4 |      1999-10-31 |
|  4 |      2 |   2.2 |      1999-10-31 |
|  5 |      3 |   6.1 |      1999-10-31 |
-----------------------------------------

Any help?

like image 354
John Isaiah Carmona Avatar asked Oct 04 '12 06:10

John Isaiah Carmona


2 Answers

You can get their maximum EffectiveDate in a subquery then join it again with its own table,

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT TypeID, MAX(EffectivityDate) maxDate
            FROM tableName
            GROUP BY TypeID
        ) b ON  a.TypeID = b.TypeID AND
                a.EffectivityDate = b.maxDate

SQLFiddle Demo

like image 190
John Woo Avatar answered Sep 26 '22 23:09

John Woo


try this:

select * 
from   your_table t
join
       (select TypeID ,max(EffectivityDate ) as EffectivityDate 
        from your_table
        group by TypeID )a
on   t.TypeID =a.TypeID 
and  t.EffectivityDate =a.EffectivityDate 
like image 25
Joe G Joseph Avatar answered Sep 22 '22 23:09

Joe G Joseph