Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 需要获取MAX中所选项目的ID_Sql_Sql Server - Fatal编程技术网

Sql 需要获取MAX中所选项目的ID

Sql 需要获取MAX中所选项目的ID,sql,sql-server,Sql,Sql Server,我有一个帐户(实体)列表,每个帐户有0:n个事件。(实体_事件) 在上面的查询中,我得到了所有事件,以及交易的最后完成日期,以及交易的总价值 我还需要的是上次支付交易的ID 我正在获取最大值(ee.event\u date)——但是有没有办法也获取实体\u事件的id?如果那天有不止一个活动,那么我想要最后一个 或者此处是否需要子查询?如果使用窗口函数而不是分组依据,则可以从记录中获取所有其他列。以下是查询的外观: select t.* from (Select e.id, e.descripti

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

在上面的查询中,我得到了所有事件,以及交易的最后完成日期,以及交易的总价值

我还需要的是上次支付交易的ID

我正在获取最大值(ee.event\u date)——但是有没有办法也获取实体\u事件的id?如果那天有不止一个活动,那么我想要最后一个


或者此处是否需要子查询?

如果使用窗口函数而不是
分组依据
,则可以从记录中获取所有其他列。以下是查询的外观:

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;

完美的现在,我们来看看为什么会这样!从未在没有组的情况下使用计数/总和/最大值。现在需要阅读“窗口功能”。谢谢
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;