DISTINCT BY MAX()?

时间:2012-10-04 06:54:01

标签: mysql sql

如何获取具有最大TypeID的不同EffectivityDate的行?

原始表

-----------------------------------------
| 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 |
-----------------------------------------

查询结果

-----------------------------------------
| 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 |
-----------------------------------------

任何帮助?

2 个答案:

答案 0 :(得分:11)

您可以在子查询中获取最大EffectiveDate,然后使用自己的表再次加入

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

答案 1 :(得分:6)

试试这个:

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