select a.billid,a.traderid,a.billdate,b.materialid,b.quantity,b.chargedate ,c.quantity as referquantity,
unreferquantity=b.quantity-isnull((select sum(Quantity) from purchasedetail e, purchase f where e.billid=f.billid and referbillid= b.billid and referitemno=b.itemno and f.billdate<=c.billdate),0),
finishdate=d.billdate,outfinishdate=case when datediff(dd,b.chargedate,d.billdate)<=0 then 0 else datediff(dd,b.chargedate,d.billdate) end,b.closed
 from porder a inner join porderdetail b on a.billid=b.billid
left join purchasedetail c on b.billid=c.referbillid and b.itemno=c.referitemno
left join purchase d on d.billid=c.billid

解决方案 »

  1.   

    运行有如下提示的 
    服务器: 消息 207,级别 16,状态 3,行 1
    列名 'billdate' 无效。
      

  2.   

    porder 表有没有哪个字段?帮你格式化一下
    SELECT  a.billid ,
            a.traderid ,
            a.billdate ,
            b.materialid ,
            b.quantity ,
            b.chargedate ,
            c.quantity AS referquantity ,
            unreferquantity = b.quantity
            - ISNULL(( SELECT   SUM(Quantity)
                       FROM     purchasedetail e ,
                                purchase f
                       WHERE    e.billid = f.billid
                                AND referbillid = b.billid
                                AND referitemno = b.itemno
                                AND f.billdate <= c.billdate
                     ), 0) ,
            finishdate = d.billdate ,
            outfinishdate = CASE WHEN DATEDIFF(dd, b.chargedate, d.billdate) <= 0
                                 THEN 0
                                 ELSE DATEDIFF(dd, b.chargedate, d.billdate)
                            END ,
            b.closed
    FROM    porder a
            INNER JOIN porderdetail b ON a.billid = b.billid
            LEFT JOIN purchasedetail c ON b.billid = c.referbillid
                                          AND b.itemno = c.referitemno
            LEFT JOIN purchase d ON d.billid = c.billid
      

  3.   

     AND f.billdate <= c.billdate  LEFT JOIN purchasedetail c ON b.billid = c.referbillid应该是这里有问题吧,因为  purchasedetail里面没有billdate, 主表purchase里面才有billdate
      

  4.   

    那就把select中的a.billdate改成c.billdate