SQL SELECT返回最近创建的日期,其中日期在第二个表

时间:2017-06-16 00:31:40

标签: sql postgresql select

我有一张产品 prdtbl 表和一张销售历史表 postdt

我需要退回最近销售日期的产品,目前我收到的重复产品列出了过去所有的销售情况,而不仅仅是最近的销售情况。

SELECT prdtbl.prdcod,
prdtbl.stkqty,
prdtbl.ordqty,
prdtbl.csoqty,
postdt.crtdat as LastPurchase
FROM (prdtbl
    LEFT JOIN postdt ON prdtbl.prdcod=postdt.itmcod)
WHERE prdtbl.prdcod NOT LIKE '*%'
AND (prdtbl.prdcod NOT LIKE 'CO%'
    or (prdtbl.prdcod LIKE 'CO%' AND prdtbl.stkqty >0 OR prdtbl.ordqty >0 OR prdtbl.csoqty >0))
AND (postdt.crtdat >= '2014-01-01'
    OR (postdt.crtdat < '2014-01-01' AND prdtbl.stkqty >0 OR prdtbl.ordqty >0 OR prdtbl.csoqty >0))
GROUP BY prdtbl.prdcod, postdt.crtdat, prdtbl.ordqty, prdtbl.stkqty, prdtbl.csoqty
ORDER BY prdtbl.prdcod DESC, MAX(postdt.crtdat) DESC

我已尝试过以下内容,但由于postdt表格非常大,这需要很长时间才能返回

AND postdt.crtdat IN ( SELECT MAX(postdt.crtdat) FROM postdt GROUP BY prdtbl.prdcod) 

在最初的SELECT查询中,我也尝试使用下面的内容,但这仍然会返回重复的产品代码

MAX(postdt.crtdat) as LastPurchase

希望这是有道理的,仍然让我了解SQL!

2 个答案:

答案 0 :(得分:0)

最近的销售日期是

SELECT MAX(crtdat) FROM postdt

具有最近销售日期的产品代码列表是

SELECT itmcod FROM postdt WHERE crtdat = (SELECT MAX(crtdat) FROM postdt)

您的查询可能看起来像这样

SELECT ...
FROM prdtbl
WHERE prdcod IN (
  SELECT itmcod FROM postdt WHERE crtdat = (SELECT MAX(crtdat) FROM postdt)
)
AND ...

确保postdt.crtdat列上有索引。

答案 1 :(得分:0)

你最好的选择是DISTINCT ON

SELECT DISTINCT ON (p.prdcod) p.prdcod, p.stkqty, p.ordqty, p.csoqty, d.crtdat as LastPurchase
FROM prdtbl p LEFT JOIN
     postdt d
     ON p.prdcod = d.itmcod
WHERE p.prdcod NOT LIKE '*%' AND
      (p.prdcod NOT LIKE 'CO%' O
       (p.prdcod LIKE 'CO%' AND p.stkqty > 0 OR p.ordqty > 0 OR p.csoqty > 0
       )
      ) AND
      (d.crtdat >= '2014-01-01' OR
       (d.crtdat < '2014-01-01' AND p.stkqty > 0 OR p.ordqty > 0 OR p.csoqty > 0
       )
      )
GROUP BY p.prdcod, d.crtdat, p.ordqty, p.stkqty, p.csoqty
ORDER BY p.prdcod DESC, p.crtdat DESC;

每个产品返回一行,最近的销售额为ata。