所以我有三个表(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
谢谢。
答案 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
。子查询不是必需的。