簡體   English   中英

在復雜的MySQL查詢中獲取整行的MIN值

[英]Getting whole row of MIN value in complex MySQL query

我發現有幾篇文章討論了如何使用特定的MIN()值獲取表的整個行,但是我還不了解如何將其添加到我的一些復雜查詢中。

我使用它來創建視圖,所以我有一個項目表及其最低活動成本。 使用包含4列的此視圖的其他流程已經到位:ItemNumber-PL_IPRecNbr成本-價目表成本說明-PH_VndrDocumentID PriceSheet記錄號-PH_RecNbr

這是我的MySQL查詢:

SELECT `pl`.`PL_IPRecNbr` AS `PL_IPRecNbr`,
IF (min(`pl`.`PL_ATRLandedCostEach`) = 0, min(`pl`.`PL_ATRCostEach`), 
min(`pl`.`PL_ATRLandedCostEach`)) AS `Cost`,
`ph`.`PH_VndrDocumentID` AS `PH_VndrDocumentID`,
`ph`.`PH_RecNbr` AS `PH_RecNbr`
FROM `pl`
JOIN `ph` ON 
`pl`.`PL_PHRecNbr` = `ph`.`PH_RecNbr`
WHERE isnull(`ph`.`PH_ReplacedByPH_RecNbr`)
AND `ph`.`PH_ExcludeSheetFromAPS` = 'N'
AND (`pl`.`PL_PurchaseQty` > `pl`.`PL_SoldQty` OR `pl`.`PL_PurchaseQty` = 0)
AND cast(now() AS date) BETWEEN `ph`.`PH_PricesStartDate`
AND `ph`.`PH_PricesEndDate`
GROUP BY `pl`.`PL_IPRecNbr`

問題是我為“成本”獲取的值是正確的,但是我為“ PH_VndrDocumentID”和“ PH_RecNbr”獲取的值不正確。 我需要將它們作為成本所在行中的值。

我已經嘗試了許多嘗試並搜索了許多答案,但是無法將注意力集中在如何獲得所需的結果上。

表說明以供參考:

PH is a table of "Price Sheet Headers"
 - Also called just Price Sheets.
 - They are "Active when they fall into a start and end date range of today
 - There are multiple price sheets active for each item, I need the lowest one.
 - There are sometimes limits on how many items are available thats why we check to see if the purchased qty is greater than the Sold Qty. 
 - If there is no limit on items the PurchaseQty shows a 0.

PL is a tables of Prices belonging to each "PH". - Each line is a Price for an item - The price is either in one of two columns either PL_ATRLandedCostEach or PL_ATRCostEach, if Landed is 0 then its in the other column, that why the IF.

如您所見,我正在嘗試使用條件來確定最低價格和相應的價格表(PHRecNbr),該條件僅基於日期和其他因素查找有效的價格表。

任何討論或指示將是有幫助的。 先感謝您!

您的pl會始終具有ph.PH_RecNbr匹配的PL_PHRecNbr嗎? 如果是這樣,您可以終止聯接並強制使用正確的PH_VndrDocumentID PH_RecNbr(擺脫由JOIN引起的任何歧義):

SELECT
  pl.PL_IPRecNbr           AS PL_IPRecNbr,
  IF (
    min( `pl`.`PL_ATRLandedCostEach` ) = 0,
    min( `pl`.`PL_ATRCostEach` ),
    min( `pl`.`PL_ATRLandedCostEach` )
  )                        AS `Cost`,
  `ph`.`PH_VndrDocumentID` AS `PH_VndrDocumentID`,
  `ph`.`PH_RecNbr`         AS `PH_RecNbr`
FROM
  pl,
  ph
WHERE
  pl.PL_PHRecNbr = ph.PH_RecNbr     AND 
  ph.PH_ReplacedByPH_RecNbr IS NULL AND
  ph.PH_ExcludeSheetFromAPS = 'N'   AND
  pl.PL_PurchaseQty > pl.PL_SoldQty AND
  pl.PL_PurchaseQty = 0             AND 
  cast(now() AS date) BETWEEN ph.PH_PricesStartDate AND ph.PH_PricesEndDate
GROUP BY
  pl.PL_IPRecNbr

這將強制返回的每一行都基於單個pl.PL_IPRecNbr項(假設每行只有一個)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM