这个活还是让前台程序去完成吧?SQL写这个好像不好写啵,我不懂,看过一个朋友写的一样效果的,是用中间量保存chargePrice然后在结果表中逐行计算逐行更新,有点郁闷。

解决方案 »

  1.   


    create table #charge ( Billno varchar (255)  ,  sumPrice int  , billDate datetime   )insert #charge ( billno , sumprice , billdate ) values ( 'sk-001' , 500 , '2005-05-06' )
    insert #charge ( billno , sumprice , billdate ) values ( 'sk-002' , 1000 , '2005-05-07' )create table #sale ( Billno varchar (255)  ,  sumPrice int  , billDate datetime   )insert #sale ( billno , sumprice , billdate ) values ( 'xs-001' , 1000 , '2005-05-05' )
    insert #sale ( billno , sumprice , billdate ) values ( 'xs-002' , 1500 , '2005-05-08' )
    insert #sale ( billno , sumprice , billdate ) values ( 'xs-003' , 800 , '2005-05-10' )
    select T.* 
    into #tp
    from (select * from #sale union all select * from #charge) T
    order by billDateselect identity(int,1,1) as no,*
    into #tp2
    from #tpselect * from #tp2select no,
        Billno,
        case when left(Billno,2)='sk' then sumPrice else 0 end as priceLess,
        case when left(Billno,2)='xs' then sumPrice else 0 end as priceAdd,
        (select sum(case when left(Billno,2)='sk' then -1*sumPrice else sumPrice end) from #tp2 where no<=t.no) as chargePrice
    from #tp2 t
    drop table #tp,#tp2,#charge,#sale/*应收表:chargeBook
           No    BillNo  priceLess  priceAdd   chargePrice
           1     xs-001  0          1000        1000
           2     sk-001  500         0           500
           3     sk-002  1000        0           -500
           4     xs-002  0           1500        1000
           5     xs-003  0           800         1800
    */
      

  2.   

    select A.billNo,
    A.sunPrice as priceLess,
    A.sumPrice as priceAdd,
    (A.sunPrice-A.sumPrice) as chargePrice 
    from (
    select billNo,'' as sumPrice,sumPrice from sale
    union
    select billNo,sunPrice,'' from charge ) A
      

  3.   

    筆誤:select A.billNo,
    A.sunPrice as priceLess,
    A.sumPrice as priceAdd,
    (A.sunPrice-A.sumPrice) as chargePrice 
    from (
    select billNo,'' as sunPrice,sumPrice from sale
    union
    select billNo,sunPrice,'' from charge ) A
      

  4.   

    DECLARE @SALE TABLE(BILLNO VARCHAR(255), SUMPRICE INT, BILLDATE DATETIME)
    DECLARE @CHARGE TABLE(BILLNO VARCHAR(255), SUMPRICE INT, BILLDATE DATETIME)
    INSERT INTO @SALE
    SELECT 'xs-001', 1000, '2005-05-05'
    UNION
    SELECT 'xs-002', 1500, '2005-05-08'
    UNION
    SELECT 'xs-003', 800, '2005-05-10'INSERT INTO @CHARGE
    SELECT 'sk-001', 500, '2005-05-06'
    UNION
    SELECT 'sk-002', 1000, '2005-05-07'SELECT IDENTITY(INT, 1, 1) AS [No], * INTO # FROM
    (SELECT BILLNO, 0 AS PRICELESS, SUMPRICE AS PRICEADD, BILLDATE FROM @SALE
    UNION
    SELECT BILLNO, SUMPRICE AS PRICELESS, 0 AS PRICEADD, BILLDATE FROM @CHARGE) AS A
    ORDER BY BILLDATESELECT [No], BILLNO, PRICELESS, PRICEADD, (SELECT SUM(PRICEADD) - SUM(PRICELESS) FROM # WHERE BILLDATE <= A.BILLDATE) AS CHARGEPRICE FROM # AS ADROP TABLE #