需要获取MAX中选择的项目的ID

时间:2014-06-27 23:22:12

标签: sql sql-server

我有一个帐户(实体)列表,每个帐户都有0:n个事件。 (entity_event)。

Select 
    e.id,
    e.description, 
    SUM(CASE WHEN ee.source_entity_id = e.id THEN 1 ELSE -1 END * ISNULL(ee.amount,0)) AS Total, 
    MAX(ee.event_date) AS LastTransactionDate
from entity e
left join entity_event ee
on ee.source_entity_id = e.id or ee.destination_entity_id = e.id
where e.deleted is NULL
and e.portfolio_id = 79
and e.entity_type_id = 1

GROUP BY e.id, e.description
order by e.description

在上面的查询中,我收到所有事件,以及交易完成的最后日期,以及交易总金额。

我还需要的是最后一笔付款交易的ID。

我正在获取MAX(ee.event_date) - 但是有没有办法获得该entity_event的id?如果那个日期有多个事件 - 那么我想要最后一个事件。

或者在这里需要子查询吗?

1 个答案:

答案 0 :(得分:1)

如果使用窗口函数而不是group by,则可以从记录中获取所有其他列。以下是查询的内容:

select t.*
from (Select e.id, e.description, 
             SUM(CASE WHEN ee.source_entity_id = e.id THEN 1 ELSE -1 END * ISNULL(ee.amount, 0)) OVER
                 (partition by e.id) AS Total, 
             MAX(ee.event_date) over (partition by e.id) AS LastTransactionDate,
             row_number() over (partition by e.id order by ee.event_date desc) as seqnum
      from entity e left join entity_event
           ee
           on ee.source_entity_id = e.id or ee.destination_entity_id = e.id
      where e.deleted is NULL and e.portfolio_id = 79 and e.entity_type_id = 1
     ) t
where seqnum = 1;
order by e.description;