这是借出单
borrow_docno borrow_lineno borrow_date borrow_code borrow_qty
A001              10          2012-1-20           01.01.01           10
A001              20          2012-1-20           01.01.02           20
A002              30          2012-2-20           01.01.03           30
A002              20          2012-2-20     01.01.04           40

这是还入单,
back_docno  back_line  back_date  back_code back_qty      borrow_docno
b001 10 2012-2-20  01.01.01           2               A001
b002 10 2012-3-20  01.01.01           3         A001
b003 10 2012-3-28  01.01.01           4         A001
b004 20 2012-2-10  01.01.02           5         A001
b005 20 2012-2-25  01.01.02           1         A001
b006 20 2012-3-25  01.01.02           1         A001
b007 20 2012-3-26  01.01.02           1         A001一个借出单会有多个还入单,且每个月会有可能多张还入单,需要得到的结果就是把同一个月的还入单的还入数量进行累加,得到一行,而还入日期(back_date)则取最大日期或者最小日期,得到的还入单结果如下图:
back_line  back_date  back_code back_qty      borrow_docno
10 2012-2-20    01.01.01        2                A001--不同月则按原来显示
10 2012-3-28    01.01.01        7         A001 --同月还入数量进行累加,且日期以保留最大的日期20 2012-2-25    01.01.02        6         A001--同月还入数量进行累加,且日期以保留最大的日期
20 2012-3-26    01.01.02        2         A001--不同月则按原来显示

解决方案 »

  1.   

    --> 测试数据:[借出]
    go
    if object_id('borrow') is not null 
    drop table borrow
    go
    create table borrow(
    [borrow_docno] varchar(4),
    [borrow_lineno] int,
    [borrow_date] datetime,
    [borrow_code] varchar(8),
    [borrow_qty] int)
    insert borrow
    select 'A001',10,'2012-1-20','01.01.01',10 union all
    select 'A001',20,'2012-1-20','01.01.02',20 union all
    select 'A002',30,'2012-2-20','01.01.03',30 union all
    select 'A002',20,'2012-2-20','01.01.04',40
    --> 测试数据:[还入]
    go
    if object_id('[return]') is not null 
    drop table [return]
    go
    create table [return](
    [back_docno] varchar(4),
    [back_line] int,
    [back_date] datetime,
    [back_code] varchar(8),
    [back_qty] int,
    [borrow_docno] varchar(4)
    )
    go
    insert [return]
    select 'b001',10,'2012-2-20','01.01.01',2,'A001' union all
    select 'b002',10,'2012-3-20','01.01.01',3,'A001' union all
    select 'b003',10,'2012-3-28','01.01.01',4,'A001' union all
    select 'b004',20,'2012-2-10','01.01.02',5,'A001' union all
    select 'b005',20,'2012-2-25','01.01.02',1,'A001' union all
    select 'b006',20,'2012-3-25','01.01.02',1,'A001' union all
    select 'b007',20,'2012-3-26','01.01.02',1,'A001'
    select back_line,convert(varchar(10),MAX(back_date),120) as back_date,
    back_code,sum(back_qty) as back_qty,
    borrow_docno from [return] b group by back_line,month(back_date),
    back_code,borrow_docno/*
    back_line back_date back_code back_qty borrow_docno
    10 2012-02-20 01.01.01 2 A001
    10 2012-03-28 01.01.01 7 A001
    20 2012-02-25 01.01.02 6 A001
    20 2012-03-26 01.01.02 2 A001
    */