复杂的SQL取决于每个对象的插入时间?

Cap*_*ine 2 sql sql-server

嗨所以这是表:

Select * from LogTable order by insert_time desc
Run Code Online (Sandbox Code Playgroud)

LogTable:

|user_id|action|object_id|insert_time|
|2      |start |123      |20.04.2015 |
|2      |stop  |123      |19.04.2015 |
|2      |start |123      |17.04.2015 |
|1      |stop  |321      |16.04.2015 |
|1      |start |321      |12.04.2015 |
|3      |start |1234     |11.04.2015 |
|4      |start |12345    |5.04.2015  |
|4      |stop  |12345    |3.04.2015  |
...
Run Code Online (Sandbox Code Playgroud)

现在,我想选择所有具有相同对象的用户ID,但这些用户ID从未停止但从未再次启动过.因此,应选择id = 1的用户.应该如何编写SQL查询?

Gor*_*off 5

您似乎希望所有用户的最后一个值actionstop.这是一种使用方法row_number():

select lt.*
from (select lt.*,
             row_number() over (partition by user_id, object_id
                                order by insert_time desc) as seqnum
      from logtable lt
     ) lt
where seqnum = 1 and action = 'stop';
Run Code Online (Sandbox Code Playgroud)