我有一张桌子,上面看起来像这样:
ID NAME Coord
-------------------------
1 area1 bla
1 area2 bla
1 area3 bla
和一个表,其中对象的位置取决于时间:
Time_Stamp Latitude Longitude
---------------------------------------------------
2018-07-17 21:13:30.000 bla bla
2018-07-17 21:13:45.000 bla bla
2018-07-17 21:14:00.000 bla bla
2018-07-17 21:14:15.000 bla bla
2018-07-17 21:14:30.000 bla bla
2018-07-17 21:14:45.000 bla bla
2018-07-17 21:15:00.000 bla bla
2018-07-17 21:15:15.000 bla bla
2018-07-17 21:15:30.000 bla bla
2018-07-17 21:15:45.000 bla bla
2018-07-17 21:16:00.000 bla bla
从这里我选择一个对象区域每个区域的位置的结果集(类型=> 0个外部区域,1个内部区域)
TS area type
-----------------------------------------------
2018-07-17 21:13:30.000 area1 1
2018-07-17 21:13:30.000 area2 0
2018-07-17 21:13:30.000 area3 0
2018-07-17 21:13:45.000 area1 0
2018-07-17 21:13:45.000 area2 0
2018-07-17 21:13:45.000 area3 0
2018-07-17 21:14:00.000 area1 0
2018-07-17 21:14:00.000 area2 1
2018-07-17 21:14:00.000 area3 0
从该数据集中,我需要获取对象进入和离开一个区域时每个区域的时间。
TS area type
------------------------------------------
2018-07-17 21:13:30.000 area1 1
2018-07-17 21:13:45.000 area1 0
2018-07-17 21:14:00.000 area2 1
这么久...我在fetch(foreach区域)中有一个选择。
select *
from
(select
min(ts) TS,
area,
type
from
(select
*,
grp = ROW_NUMBER() OVER(ORDER BY ts) -
ROW_NUMBER() OVER(PARTITION BY type ORDER BY ts)
from
@t
where
area = @area -- this is area from fetch and
-- @t is the table I've built first
) a
group by
grp, type, area) b
order by
endtime
如果可能的话,我需要一种解决方案来避免获取。
答案 0 :(得分:2)
我认为您只需要partition by
:
select min(ts) as TS, area, type
from (select t.*,
(row_number() over (partition by area order by ts) -
row_number() over (partition by area, type order by ts)
) as grp
from @t t
) t
group by grp, type, area
order by min(ts) desc;
外部查询不是必需的-子查询中始终没有定义endtime
。