我有两个表,它们都有时间按,日期,桩号的记录。(这三个作为主键)
现在,需要把它们联在一张表中,需要的是,首先,查询两个表中日期的记录,首先要保证日期相同,然后,查询时间,要保证时间相差最小的记录联起来放在一个表中。
请问怎么实现?
比如,表1的时间是10:10,10:15,10:20,10:25等一系列5分钟为间隔的数据时间 
表2的时间按是10:12,10:14 ,10:16等一系列以2分钟为间隔的数据时间
谢谢各位高手了。

解决方案 »

  1.   

    /*
    我有两个表,它们都有时间按,日期,桩号的记录。(这三个作为主键)
    现在,需要把它们联在一张表中,需要的是,首先,查询两个表中日期的记录,首先要保
    证日期相同,然后,查询时间,要保证时间相差最小的记录联起来放在一个表中。
    请问怎么实现?
    比如,表1的时间是10:10,10:15,10:20,10:25等一系列5分钟为间隔的数据时间 
    表2的时间按是10:12,10:14 ,10:16等一系列以2分钟为间隔的数据时间
    谢谢各位高手了。
    */create table table1(date1 datetime)
    create table table2(date2 datetime)
    insert table1 select '2006-07-05 10:10'
    union all select '2006-07-05 10:15'
    union all select '2006-07-06 10:10'
    union all select '2006-07-06 10:15'
    union all select '2006-07-06 10:20'
    union all select '2006-07-06 10:25'insert table2 select '2006-07-06 10:12'
    union all select '2006-07-06 10:14'
    union all select '2006-07-06 10:16'
    union all select '2006-07-06 10:18'
    union all select '2006-07-06 10:20'
    union all select '2006-07-06 10:22'select top 1 t1.date1,t2.date2,min(datepart(minute,t1.date1-t2.date2)) [interval] from table1 t1,table2 t2
    group by  t1.date1,t2.date2
    order by min(datepart(minute,t1.date1-t2.date2)) asc
    /*
    date1                                                  date2                                                  interval    
    ------------------------------------------------------ ------------------------------------------------------ ----------- 
    2006-07-06 10:20:00.000                                2006-07-06 10:20:00.000                                0
    */
    drop table table1
    drop table table2