sql - Need to get ID of an item selected in a MAX -
i have list of accounts (entities), , each account has 0:n events. (entity_event).
select e.id, e.description, sum(case when ee.source_entity_id = e.id 1 else -1 end * isnull(ee.amount,0)) total, max(ee.event_date) lasttransactiondate entity e left join entity_event ee on ee.source_entity_id = e.id or ee.destination_entity_id = e.id e.deleted null , e.portfolio_id = 79 , e.entity_type_id = 1 group e.id, e.description order e.description
in above query, getting events, along last date transaction done on, total amount worth of transactions.
what need, id of last paid transaction.
i getting max(ee.event_date) - there way id of entity_event well? if there's more 1 event on date - want last one.
or need sub queries here?
if use window functions instead of group by
, can fetch other columns record. here query looks like:
select t.* (select e.id, e.description, sum(case when ee.source_entity_id = e.id 1 else -1 end * isnull(ee.amount, 0)) on (partition e.id) total, max(ee.event_date) on (partition e.id) lasttransactiondate, row_number() on (partition e.id order ee.event_date desc) seqnum entity e left join entity_event ee on ee.source_entity_id = e.id or ee.destination_entity_id = e.id e.deleted null , e.portfolio_id = 79 , e.entity_type_id = 1 ) t seqnum = 1; order e.description;
Comments
Post a Comment