PL SQL - 加入2个表并从右表返回最大值

时间:2013-04-02 16:52:43

标签: max

尝试在右表中检索MAX文档。

SELECT   F43.PDDOCO, 
     F43.PDSFXO, 
     F43.PDLNID,
     F43.PDAREC/100 As Received, 
     F431.PRAREC/100,
     max(F431.PRDOC)

FROM     PRODDTA.F43121 F431
     LEFT OUTER JOIN PRODDTA.F4311 F43
      ON 
          F43.PDKCOO=F431.PRKCOO 
      AND F43.PDDOCO=F431.PRDOCO 
      AND F43.PDDCTO=F431.PRDCTO 
      AND F43.PDSFXO=F431.PRSFXO 
      AND F43.PDLNID=F431.PRLNID 
WHERE   F431.PRDOCO = 401531
and     F431.PRMATC = 2
and     F43.PDLNTY = 'DC'

Group by 

     F43.PDDOCO, 
     F43.PDSFXO, 
     F43.PDLNID,
     F43.PDAREC, 
     F431.PRAREC/100

此查询仍在返回右表中的两行。相当新的SQL和挣扎的声明。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果没有看到您的数据,很难分辨出问题所在,所以我会提供一些可能有用的建议。

首先,您要加入LEFT JOIN上的PRODDTA.F4311,但您在WHERE子句中有该表的过滤器。您应该将F43.PDLNTY = 'DC'移动到JOIN条件。这导致查询的行为类似于INNER JOIN

其次,您可以尝试使用子查询来获取MAX(PRDOC)值。然后,您可以限制要分组的列,这可以消除重复项。查询将类似于以下内容:

SELECT F43.PDDOCO, 
  F43.PDSFXO, 
  F43.PDLNID,
  F43.PDAREC/100 As Received, 
  F431.PRAREC/100,
  F431.PRDOC
FROM PRODDTA.F43121 F431
INNER JOIN
(
  -- subquery to get the max
  -- then group by the distinct columns
  SELECT PDKCOO, max(PRDOC) MaxPRDOC
  FROM PRODDTA.F43121
  WHERE PRDOCO = 401531
    and PRMATC = 2
  GROUP BY PDKCOO
) f2
  -- join the subquery result back to the PRODDTA.F43121 table
  on F431.PRDOC = f2.MaxPRDOC
  AND F431.PDKCOO = f2.PDKCOO
LEFT OUTER JOIN PRODDTA.F4311 F43
  ON F43.PDKCOO=F431.PRKCOO 
  AND F43.PDDOCO=F431.PRDOCO 
  AND F43.PDDCTO=F431.PRDCTO 
  AND F43.PDSFXO=F431.PRSFXO 
  AND F43.PDLNID=F431.PRLNID 
  AND F43.PDLNTY = 'DC'  -- move this filter to the join instead of the WHERE
WHERE F431.PRDOCO = 401531
  and F431.PRMATC = 2

如果您提供表格结构和一些示例数据,则更容易确定问题。