使用row_number()
和group by
爲min(dt)
每address
:
注:如果一個人在同一地址之間移動這將無法正常工作。
select
Person_id
, dt = convert(char(10),dt,120)
, Address
from (
select
person_id
, dt = min(dt)
, address
, rn = row_number() over (partition by person_id order by min(dt))
from t
group by person_id, address
) s
where rn = 3
rextester演示:http://rextester.com/VLTUU16478
回報:
+-----------+------------+---------+
| Person_id | dt | Address |
+-----------+------------+---------+
| 1 | 2016-07-16 | 2 |
| 2 | 2016-07-18 | 6 |
+-----------+------------+---------+
要一個人在同一地址之間移動正確地解決這個問題,你必須解決的差距和島嶼問題。
添加一個額外的子查詢上述解決方案,因此我們可以通過島嶼識別和組:
select
Person_id
, dt = convert(char(10),dt,120)
, Address
from (
select
person_id
, dt = min(dt)
, address
, rn = row_number() over (partition by person_id order by min(dt))
from (
select
person_id
, address
, dt
, island = row_number() over (partition by person_id order by dt)
- row_number() over (partition by person_id, address order by dt)
from t
) s
group by person_id, address, island
) s
where rn = 3
rextester演示:http://rextester.com/PPIH49666
回報:
+-----------+------------+---------+
| Person_id | dt | Address |
+-----------+------------+---------+
| 1 | 2016-07-16 | 3 |
| 2 | 2016-07-18 | 5 |
+-----------+------------+---------+
。你有解決方案嗎?謝謝! – Ice
@Ice更新第二個解決方案來解決差距和孤島問題。 – SqlZim