连接多个表时出错

时间:2017-04-17 07:12:11

标签: sql-server

SELECT 
    refnum as pornum,  tmp_Extract.matnum, matm.matmdescription,
    matm.extradescription, 
    SUM(sqty) AS porqty, CAST(SUM(dqty) AS numeric(16,4)) AS grnqty,   
    (sum(sqty) - sum(dqty)) AS balqty,
    (sum(sorqty) - sum(dorqty)) as balbaseqty,
    puom, pcfactor, apnum   
FROM 
    (SELECT  
         matnum, matmdescription1, isnull(pqty,0) AS sqty, 0 AS dqty,   
         refnum, isnull(qty, 0) as sorqty, 0 as dorqty, 
         puom, pcfactor, apnum, porextractmark 
     FROM 
         por1  
     WHERE
         ((por1.clearflag IS NULL OR por1.clearflag = 0) 
         AND (por1.status <> 'V'))  

UNION ALL               SELECT deliverydate FROM porh               其中((porh.flag ='POR'))和((porh.status ='P'))

UNION ALL

     SELECT  
         matnum, matmdescription1, 0 AS sqty, isnull(pqty / porpcfactor, 0) AS dqty, 
         pornum AS refnum, 0 as sorqty, isnull(qty,0) as dorqty,    
         puom, porpcfactor as pcfactor, apnum, porextractmark   
     FROM 
         dbo.grn1       
     WHERE
         grn1.refnum NOT IN (SELECT refnum 
                             FROM grnh 
                             WHERE grnh.status = 'v')) AS tmp_Extract  
LEFT JOIN (
(SELECT matnum, MAX(deliverydate) as deliverydate FROM porh GROUP BY matnum) 
AS tmp_Extract

LEFT JOIN matm on matm.matnum = tmp_Extract.matnum 
where refnum like '%POR%'
GROUP BY refnum, tmp_Extract.matnum,tmp_Extract.puom,tmp_Extract.pcfactor,
apnum,matm.matmdescription,matm.extradescription,
tmp_Extract.deliverydate
having sum(sqty)>sum(dqty)                                         

我想加入表格porh的送货日期,但无法解决问题。

0 个答案:

没有答案