如果把时间表和数据表结合查询?
时间表1
序号     开始时间     结束时间
12       1951-01-05   1951-01-06
13       1951-01-05   1951-01-07
.......数据表2:
站号         日期            数据
59845        1951-01-05      2
59845        1951-01-06      4
59845        1951-01-07      3
59846        1951-01-05      10
59846        1951-01-06      2
59846        1951-01-07      5
......现想得到下表:
序号  站号     总数据
12    59845     6
12    59846     12
13    59845     9
13    59846     17          
.......

解决方案 »

  1.   

    select a.序号,b.站号,SUM(b.数据) as 总数据
    from 时间表 as a ,数据表 as b 
    where a.开始时间<=b.日期 and a.结束时间>=b.日期
    group by a.序号,b.站号
      

  2.   


    --> 测试数据:[t1]
    if object_id('[t1]') is not null drop table [t1]
    create table [t1]([序号] int,[开始时间] datetime,[结束时间] datetime)
    insert [t1]
    select 12,'1951-01-05','1951-01-06' union all
    select 13,'1951-01-05','1951-01-07'
    --> 测试数据:[t2]
    if object_id('[t2]') is not null drop table [t2]
    create table [t2]([站号] int,[日期] datetime,[数据] int)
    insert [t2]
    select 59845,'1951-01-05',2 union all
    select 59845,'1951-01-06',4 union all
    select 59845,'1951-01-07',3 union all
    select 59846,'1951-01-05',10 union all
    select 59846,'1951-01-06',2 union all
    select 59846,'1951-01-07',5goselect
    a.序号,b.站号,sum(b.数据) as 总数据
    from [t1] a inner join [t2] b on b.日期 between a.开始时间 and a.结束时间
    group by a.序号,b.站号 order by 1
    /*
    序号          站号          总数据
    ----------- ----------- -----------
    12          59845       6
    12          59846       12
    13          59845       9
    13          59846       17(4 行受影响)
    */