嗨所以这是表:
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查询?
您似乎希望所有用户的最后一个值action是stop.这是一种使用方法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)
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |