Raggruppamento in t-sql con le ultime date
Domanda
Ho una tabella come questa
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 |
Per ogni contratto devo recuperare l'ultimo evento e l'importo associato all'evento e ottenere qualcosa del genere
Event ID | Contract ID | Event date | Amount | ---------------------------------------------- 3 | 1 | 2009-01-03 | 50 | 5 | 2 | 2009-01-04 | 30 |
Non riesco a capire come raggruppare correttamente i dati. Qualche idea?
Grazie in anticipo.
Soluzione
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow