我想从一个停车场做一个报告,使用这个停车场,当我调用查询的时候,可以得到里面的车。
假设我们有两个入口和两个出口,那么我在SQL中如何才能使停车场内只有汽车。
我怎样才能得到这个值?
我的表的记录示例:
id lic plate date lane access id_user
__________________________________________________________________
10 1234-BK 2020-08-11 12:24:00.000 1 OK 4
11 1234-BK 2020-08-11 12:25:00.000 3 OK 4
在这个例子中,我们假设这辆车离开了停车场,因为车道1来自入口,车道3来自出口,所以我们拥有的最后一个记录是来自出口车道。
有了这些信息,你能指导我做这个查询,让所有的车都在里面吗?
发布于 2020-08-11 20:11:00
您应该存储车辆是否进入或离开。对于这样的应用程序来说,这似乎是非常基础的。
如果你没有,你可以计算到给定时间的记录数,如果值是奇数,汽车就在里面,甚至在外面。所以要把车开进去:
select lic_plate
from t
where date < @date
group by lic_plate
having count(*) % 2 = 1;
如果您有入口和出口通道,则可以使用相关子查询获取最后一条记录,并检查最终的长枪:
select t.*
from t
where t.date = (select max(t2.date)
from t t2
where t2.lic_plate = t.lic_plate and
t2.date < @date
) and
t.lane = 1; -- last lane is an entrance lane
发布于 2020-08-11 20:33:23
要获得每个“lic_plate”的最后一个“通道”是通道1的行时,操作可以使用窗口函数。
;with get_max_cte as (
select t.*, ROW_NUMBER() over (partition by lic_plate order by t.[date] desc) rn)
select * from get_max_cte
where rn=1 and lane=1
https://stackoverflow.com/questions/63357782
复制相似问题