日期:2014-05-18  浏览次数:20616 次

高手请进,复杂查询(在线等)
我有一个flow表,里面有个name,starttime,flowtype字段,其中flowtype这个字段的值有:跑出,跳出,走出,跑进,跳进,走进。
      name                 starttime                                       flowtype
  兔子                     2007-07-05   10:22:00               跑出
  老虎                     2007-07-05   11:22:00               跑进
    兔子                   2007-07-06     10:45:00             跑进
   

    我现在要根据指定的name,将“跑出”所对应的第一条“进”的状态合并为一条记录。
比如:
兔子     2007-07-05   10:22:00     跑出       2007-07-06     10:45:00             跑进

------解决方案--------------------
select a.name, a.starttime ,a.flowtype, min(b.flowtype)
from flow a left join flow b
on a.name = b.name and a.starttime <b.starttime
group by a.name, a.starttime ,a.flowtype
------解决方案--------------------
select a.*,c.flow_type
from(
select a.name, a.starttime ,a.flowtype, min(b.starttime) in_time
from flow a left join (select * from flow where flowtype like '%进 ')b
on a.name = b.name and a.starttime <b.starttime
where a.name= '兔子 '
group by a.name, a.starttime ,a.flowtype
) a
join flow c on a.name=c.name and a.in_time=c.in_time

------解决方案--------------------
-- 我这写了一个,超复杂,最好你把它简化一下改造成函数比较好
declare @table table([name] nvarchar(10),starttime datetime,flowtype nvarchar(2))
insert @table
select N '兔子 ', '2007-07-05 10:22:00 ',N '跑出 ' union all
select N '老虎 ', '2007-07-05 11:22:00 ',N '跑进 ' union all
select N '兔子 ', '2007-07-06 10:45:00 ',N '跑进 ' union all
select N '老虎 ', '2007-07-06 12:00:00 ',N '走出 ' union all
select N '老虎 ', '2007-07-06 12:40:00 ',N '跳进 '

select aa.name,aa.outtime,aa.out_put,aa.intime,bb.in_put
from
(select a.name,a.outtime,a.out_put,dateadd(minute,a.diff,a.outtime)as intime
from
(select OUT_PUT.name,OUT_PUT.outtime,OUT_PUT.out_put,
min(datediff(minute,OUT_PUT.outtime,IN_PUT.intime))as diff
from
(select name,starttime as outtime,flowtype as out_put
from @table
where flowtype in( '走出 ', '跑出 ', '跳出 '))OUT_PUT
inner join
(select name,starttime as intime,flowtype as in_put
from @table
where flowtype in( '走进 ', '跑进 ', '跳进 '))IN_PUT

on OUT_PUT.name=IN_PUT.name AND OUT_PUT.outtime <IN_PUT.intime

group by OUT_PUT.name,OUT_PUT.outtime,OUT_PUT.out_put)a )aa
inner join
(select name,starttime as intime,flowtype as in_put
from @table
where flowtype in( '走进 ', '跑进 ', '跳进 '))bb
on aa.name=bb.name and aa.intime=bb.intime



------解决方案--------------------
--建立测试环境
create table 表1
([name] nvarchar(10),starttime datetime,flowtype nvarchar(2))
GO
insert 表1
select N '兔子 ', '2007-07-05 10:22:00 ',N '跑出 ' union all
select N '老虎 ', '2007-07-05 11