5

如何获得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 |
-----------------------------------------

有什么帮助吗?

4

2 回答 2

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

于 2012-10-04T06:55:32.123 回答
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 
于 2012-10-04T06:56:12.507 回答