SQL2000
有这样一个表a
入  日期           数量
入     20100101        10
入     20100108        10
入     20100201        30
入     20100601        10
入     20100901        10表b
出  日期           数量
出     20100101        1
出     20100105        2
出     20100107        5
出     20100701        5
出     20100906        6我想得到一个根据A表的日期段汇总表,截止10月1
入出     日期段                   入       出
入出     20100101-20100108        10       8      
入出     20100108-20100201        10       0
入出     20100201-20100601        30       0
入出     20100601-20100901        10       5
入出     20100901-20101001        10       6
我想把这个日期分段

解决方案 »

  1.   

    --> 测试数据:#a
    if object_id('tempdb.dbo.#a') is not null drop table #a
    create table #a(日期 datetime, 数量 int)
    insert into #a
    select '20100101', 10 union all
    select '20100108', 10 union all
    select '20100201', 30 union all
    select '20100601', 10 union all
    select '20100901', 10
    --> 测试数据:#b
    if object_id('tempdb.dbo.#b') is not null drop table #b
    create table #b(日期 datetime, 数量 int)
    insert into #b
    select '20100101', 1 union all
    select '20100105', 2 union all
    select '20100107', 5 union all
    select '20100701', 5 union all
    select '20100906', 6select a.bd+'-'+a.ed 日期段, max(a.数量)入, sum(isnull(b.数量,0))出 from
    (
    select convert(varchar,日期,112)bd, 数量,
    (select isnull(convert(varchar,min(日期),112),'20101001') from #a where 日期>t.日期 and 日期<'20101001')ed
    from #a t
    ) a
    left join #b b on b.日期>=a.bd and b.日期<a.ed
    group by a.bd+'-'+a.ed
    select * from #a/*
    日期段            入          出
    ----------------- ----------- -----------
    20100101-20100108 10          8
    20100108-20100201 10          0
    20100201-20100601 30          0
    20100601-20100901 10          5
    20100901-20101001 10          6
    */
      

  2.   

    select a.bd+'-'+a.ed 日期段, max(a.数量)入, sum(isnull(b.数量,0))出 from
    (
    select convert(varchar,日期,112)bd, 数量,
    (select isnull(convert(varchar,min(日期),112),'20101001') from #a where 日期>t.日期 and 日期<'20101001')ed
    from #a t
    ) a
    left join #b b on b.日期>=a.bd and b.日期<a.ed
    group by a.bd+'-'+a.ed/*
    日期段            入          出
    ----------------- ----------- -----------
    20100101-20100108 10          8
    20100108-20100201 10          0
    20100201-20100601 30          0
    20100601-20100901 10          5
    20100901-20101001 10          6
    */