首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

!一个SQL查询题

2012-03-22 
求助!一个SQL查询题在sqlserver 中, 表结构如下:车辆ID,gpstime,oil(油量),12011-06-23 11:11:005012011-0

求助!一个SQL查询题
在sqlserver 中, 表结构如下:
车辆ID,gpstime, oil(油量),
1 2011-06-23 11:11:00 50
1 2011-06-23 11:12:00 50
1 2011-06-23 11:13:00 50
1 2011-06-23 11:14:00 50
1 2011-06-23 11:15:00 50
1 2011-06-23 11:16:00 50
1 2011-06-23 11:17:00 50
1 2011-06-23 11:18:00 60
1 2011-06-23 11:19:00 90
1 2011-06-23 11:20:00 100
1 2011-06-23 11:21:00 99
1 2011-06-23 11:22:00 99
1 2011-06-23 11:23:00 99
2 2011-06-23 11:20:00 100
2 2011-06-23 11:21:00 99
2 2011-06-23 11:22:00 99
2 2011-06-23 11:23:00 99


油量在几分钟变化比较大,证明是在加油,
怎么查询某辆车是否在加油?加了多少油?
数据量比较大,有上W条。

[解决办法]
哪辆车在加油,加了多少油,这个简单,只需要做个自关联就行:
如:
select b.id,max(b.oil-a.oil)
from
(select id,time,oil from ceshi) as a,
(select id,time,oil from ceshi) as b
where a.id = b.id and b.time >a.time
and (b.oil-a.oil) > 0
group by b.id;
至于油量在几分钟变化比较大,证明是在加油,这个稍微复杂点,因为你提供的资料太少,
首先这三个字段哪个是唯一约束的,看上述内容权且认为时间是唯一的,而且是每分钟检测一次,权且把时间数据库属性类型当作datetime类型。
则:
select zt.id,zt.jtime,bt.maxoil from ceshi as zt,
(
select b.jtime,max(b.oil-a.oil) as maxoil
from
(select id,jtime,oil from ceshi) as a,
(select id,jtime,oil from ceshi) as b
where a.id = b.id and b.jtime = (a.jtime+1 minute)
and (b.oil-a.oil) > 0
group by b.jtime
) as bt
where zt.jtime = bt.jtime
此方法可以查询出油量有变化的时间段,及变化的油量,如果要查出具体哪一辆车哪一时间段变化最大,及变化值,再关联下即可
如:
select dd.id,dd.jtime,tt.maxoil from
(
select ht.id,max(ht.maxoil) as maxoil from
(
select zt.id,zt.jtime,bt.maxoil from ceshi as zt,
(
select b.jtime,max(b.oil-a.oil) as maxoil from
(select id,jtime,oil from ceshi) as a,
(select id,jtime,oil from ceshi) as b
where a.id = b.id and b.jtime = (a.jtime+1 minute)
and (b.oil-a.oil) > 0
group by b.jtime
) as bt
where zt.jtime = bt.jtime 
)as ht
group by ht.id
) as tt,
(
select zt.id,zt.jtime,bt.maxoil from ceshi as zt,
(
select b.jtime,max(b.oil-a.oil) as maxoil
from
(select id,jtime,oil from ceshi) as a,
(select id,jtime,oil from ceshi) as b
where a.id = b.id and b.jtime = (a.jtime+1 minute)
and (b.oil-a.oil) > 0
group by b.jtime
) as bt
where zt.jtime = bt.jtime 
) as dd
where tt.maxoil = dd.maxoil;

备注: a.jtime+1 minute 此方法是db2数据库中加一分钟的处理,如果是sqlserver,用dateadd(minute,1,a.jtime)即可,如果数据库是字符串类型,也可用截取字符串的方式。

热点排行