一个表为订单   dd(ddnum,dddate,qty) 100万条记录 ddnum为订单号,dddate为订单交货期限,qty为订单总数量
一个表收货记录 sh(ddnum,shdate,qty) 150万条记录 ,ddnum为订单号,shdate为收货时间,qty为收货数量
一个表退货记录 th(ddnum,thdate,qty) 5万条记录 ,ddnum为订单号,thdate为退货时间,qty为退货数量现求一条SQL 得到过了订单收货期限而还没送够货的订单(要减去退货的,过了期限退货的不算)。
数据库用ODBC连接的,不能写储存过程序,并只能一条SQL实现,请教....dd(ddnum,dddate,qty)
1001 2012-1-5 500 (这个订单是期限内送够货的)
1002 2012-1-5 800 (这个订单是期限内没送够货的)sh(ddnum,shdate,qty)
1001 2012-1-4 500
1001 2012-1-5 100
1002 2012-1-3 300
1002 2012-1-4 500
1002 2012-1-8 100th(ddnum,thdate,qty)
1001 2012-1-4 100
1001 2012-1-6 100 (这条不算)
1002 2012-1-5 100

解决方案 »

  1.   

    USE [CSDN]
    GOif OBJECT_ID('dd') is not null Drop table dd;
    if OBJECT_ID('sh') is not null Drop table sh;
    if OBJECT_ID('th') is not null Drop table th;CREATE TABLE dd(ddnum varchar(4), dddate datetime, qty int);
    CREATE TABLE sh(ddnum varchar(4), shdate datetime, qty int);
    CREATE TABLE th(ddnum varchar(4), thdate datetime, qty int);insert into dd(ddnum,dddate,qty)
    select '1001', '2012-1-5', 500 union all
    select '1002', '2012-1-5', 800;insert into sh(ddnum,shdate,qty)
    select '1001', '2012-1-4', 500 union all
    select '1001', '2012-1-5', 100 union all
    select '1002', '2012-1-3', 300 union all
    select '1002', '2012-1-4', 500 union all
    select '1002', '2012-1-8', 100;insert into th(ddnum,thdate,qty)
    select '1001', '2012-1-4', 100 union all
    select '1001', '2012-1-6', 100 union all
    select '1002', '2012-1-5', 100;select t1.*
    from dd t1
    join
    (
    select ddnum, sum(qty) as total
    from ( select b.* 
    from dd a
    join (
    select * from sh
    union all
    select ddnum,thdate,qty*(-1) from th
    ) b
    on a.ddnum = b.ddnum and a.dddate >= b.shdate
      ) c
    group by ddnum
    ) t2
    on t1.ddnum=t2.ddnum and t2.total < t1.qty
    /*
    ddnum dddate                  qty
    ----- ----------------------- -----------
    1002  2012-01-05 00:00:00.000 800
    */