使用最新日期对t-sql进行分组

时间:2009-06-16 11:04:51

标签: tsql grouping

我有一张这样的表

Event ID | Contract ID | Event date | Amount |
----------------------------------------------
1        | 1           | 2009-01-01 |    100 |
2        | 1           | 2009-01-02 |     20 |
3        | 1           | 2009-01-03 |     50 |
4        | 2           | 2009-01-01 |     80 |
5        | 2           | 2009-01-04 |     30 |

对于每个合约,我需要获取与事件相关的最新事件和金额,并获得类似的内容

Event ID | Contract ID | Event date | Amount |
----------------------------------------------
3        | 1           | 2009-01-03 |     50 |
5        | 2           | 2009-01-04 |     30 |

我无法弄清楚如何正确分组数据。有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:8)

SQL 2k5 / 2k8:

with cte_ranked as (
 select *
    , row_number() over (
         partition by ContractId order by EvantDate desc) as [rank]
    from [table])
select * 
   from cte_ranked
   where [rank] = 1;

SQL 2k:

 select t.*
    from table as t
    join (
        select max(EventDate) as MaxDate
            , ContractId 
            from table 
            group by ContractId) as mt
       on t.ContractId = mt.ContractId
          and t.EventDate = mt.MaxDate