如何从组中获取带有最小值的行,并从另一个表中获取相关的值?

时间:2019-06-15 19:52:55

标签: sql postgresql plpgsql

所以我有三个表(Products,Stock和ProductsBatches),我试图获取每个产品的第一个过期的批次(来自ProductsBatches),以及来自Products(例如产品名称)和Stock(例如总计)的一些其他信息数量)

我设法只获得每种产品的最早日期,但是当我添加其他列并加入时,它弄乱了日期,并给我各种各样的日期。

PRODUCTS  TABLE: 

   | PRODUCT ID (PK)|  NAME  | PRICE |    
   |     1          | CHEESE | 12.0  |

STOCK TABLE :

   | PRODUCT ID (PFK)| TOTAL QUANTITY |
   |     1           |      100       |

PRODUCTS BATCHES TABLE:

   | PRODUCT ID (PFK) | BATCH (PFK) | BATCH QUANTITY | BATCH EXPIRY |    
   |     1            |   XYZ       |       50       |  2019-01-01  |
   |     1            |   XZZ       |       50       |  2020-01-01  |

到目前为止,我已经知道:

| PRODUCT ID | BATCH EXPIRY |
|            |              |
|     1      | 2019-01-01   | 

使用SELECT productID,min(batchExpiry) from PRODUCTSBATCHES group by (productID)

我需要什么:

|PRODUCT ID| NAME |TOTAL QUANTITY|PRICE|BATCH|BATCH QUANTITY|BATCH EXPIRY|
|     1    |CHEESE|        100   |12.0 | XYZ |  50          | 2019-01-01 |

我尝试过,但也不是很好:

SELECT DISTINCT ON (b.productID) b.productID, p.name, s.totalquantity, 
p.price, b.batch, b.batchquantity, b.batchExpiry 
FROM productsbatches as b 
INNER JOIN ( 
  SELECT productID,min(batchExpiry) from PRODUCTSBATCHES group by (productID)
) as exmin b.productID = exmin.productID 
INNER JOIN stock as s ON b.productID = s.productID 
INNER JOIN products as p ON s.productID = p.productID

谢谢。

2 个答案:

答案 0 :(得分:0)

您已经很亲密,但是您忘记将batchExpiry列与子查询派生的最小值batchExpiry结合在一起:

SELECT 
  p.productID, p.name, s.totalquantity, 
  p.price, b.batch, b.batchquantity, b.batchExpiry
FROM products as p
INNER JOIN stock as s ON p.productID = s.productID 
INNER JOIN productsbatches as b ON p.productID = b.productID 
INNER JOIN ( 
  SELECT productID, min(batchExpiry) as batchExpiry 
  FROM PRODUCTSBATCHES 
  GROUP BY productID
) as exmin ON b.productID = exmin.productID AND b.batchExpiry = exmin.batchExpiry

答案 1 :(得分:0)

DISTINCT ON是正确的方法。您只需要正确使用它即可:

SELECT DISTINCT ON (p.productID) p.productID, p.name, s.totalquantity, 
       p.price, b.batch, pb.batchquantity, pb.batchExpiry
FROM products p INNER JOIN
     stock s
     ON p.productID = s.productID INNER JOIN
     productsbatches pb
     ON pb.productID = p.productID 
ORDER BY p.productID, pb.batchExpiry;

基本上,您只需要ORDER BY。子查询不是必需的。