求教一个SQL语句实现,也许有点难度。。 望不吝指教
table:
id time
a 2006-01-01 01:00:34 1
a 2006-01-01 01:00:33
a 2006-01-01 01:00:32
b 2006-01-01 01:00:31 2
b 2006-01-01 01:00:30
c 2006-01-01 01:00:20
c 2006-01-01 01:00:10
b 2006-01-01 01:00:04
b 2006-01-01 01:00:03 4
a 2006-01-01 01:00:02 3
a 2006-01-01 00:45:00
d 2006-01-01 00:40:50
f 2006-01-01 00:40:40
a 2006-01-01 00:30:30 5
a 2006-01-01 00:30:20
b 2006-01-01 00:30:10 6
b 2006-01-01 00:30:06
t 2006-01-01 00:30:03
...
如果已经查出 MAX(time) where id='a' 大于 MAX(time) where id='b' (记录 1,2)
那么需要查询最近一次 MAX(time) where id='a' 并且 必须 记录在 2 之后(时间比2早,即查出3)怎么查?
更进一步,查出3后,要查离 3最近且比3更新的(紧挨3)b的时间 4,怎么查到??
最后,需要查询整表得出的结果为:
flag time_a time_b
其中,flag标识 time_a 是否 大于 time_b ,重要的是, time_a ,time_b 必须是 1,2 或 3,4 这样成对的,符合以上所述规则的记录
由此下推,3,4 后面的 5,6 需要是 像 1,2那样 time_b时间比 time_a 时间早的
不知如何解决,
多谢!!
问题点数:20、回复次数:2Top
1 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2006-02-25 22:34:41 得分 18
declare @t table(id char(1),time datetime)
insert into @t select 'a', '2006-01-01 01:00:34'-- 1
insert into @t select 'a', '2006-01-01 01:00:33'
insert into @t select 'a', '2006-01-01 01:00:32'
insert into @t select 'b', '2006-01-01 01:00:31'-- 2
insert into @t select 'b', '2006-01-01 01:00:30'
insert into @t select 'c', '2006-01-01 01:00:20'
insert into @t select 'c', '2006-01-01 01:00:10'
insert into @t select 'b', '2006-01-01 01:00:04'
insert into @t select 'b', '2006-01-01 01:00:03'-- 4
insert into @t select 'a', '2006-01-01 01:00:02'-- 3
insert into @t select 'a', '2006-01-01 00:45:00'
insert into @t select 'd', '2006-01-01 00:40:50'
insert into @t select 'f', '2006-01-01 00:40:40'
insert into @t select 'a', '2006-01-01 00:30:30'-- 5
insert into @t select 'a', '2006-01-01 00:30:20'
insert into @t select 'b', '2006-01-01 00:30:10'-- 6
insert into @t select 'b', '2006-01-01 00:30:06'
insert into @t select 't', '2006-01-01 00:30:03'
--1、
select
top 1 *
from
@t
where
id='a' and time<(select max(time) from @t where id='b')
order by time desc
--2、
select
top 1 *
from
@t
where
id='b'
and
(select
max(time)
from
@t
where
id='a' and time<(select max(time) from @t where id='b'))<time
order by timeTop
2 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2006-02-25 22:36:48 得分 2
哦,没仔细看问题。Top




