我有兩個屬性 productType 和 Profits。目前,回傳所有包含 productType 及其利潤的行。我只想要利潤最大的行。因此,我在第二個屬性周圍使用了 MAX(),它計算我資料庫中其他表的利潤。但是,輸出仍在列印所有行,MAX() 似乎不起作用。
SELECT
outerP.prodType AS PType,
MAX((SELECT
SUM(ProductPrice.Price)
FROM
ProductPrice
WHERE
ProductPrice.ProdType = outerP.prodType) - (SELECT
SUM(TotalPartCost)
FROM
PartsPurchase
WHERE
PartsPurchase.ProductID IN (SELECT
ProductID
FROM
Product
WHERE
Product.prodType = outerP.prodType))) AS Profit
FROM
Product AS outerP
INNER JOIN
ProductPrice ON (outerP.prodType = ProductPrice.ProdType
AND outerP.Style = ProductPrice.Style)
GROUP BY outerP.prodType
當前輸出: 'Phone','120??.92999935150146' 'Tablet','159.89999675750732'
預期輸出: '平板電腦','159.89999675750732'
我嘗試將 MAX() 放在第二個屬性周圍。我什至嘗試在上述查詢周圍包裝一個新的 SELECT 陳述句以查找 MAX() 但它不起作用。無論如何,它都會輸出所有行。
uj5u.com熱心網友回復:
您可以使用ORDER BY profit并LIMIT獲得想要的結果
SELECT
outerP.prodType AS PType,
MAX((SELECT
SUM(ProductPrice.Price)
FROM
ProductPrice
WHERE
ProductPrice.ProdType = outerP.prodType) - (SELECT
SUM(TotalPartCost)
FROM
PartsPurchase
WHERE
PartsPurchase.ProductID IN (SELECT
ProductID
FROM
Product
WHERE
Product.prodType = outerP.prodType))) AS Profit
FROM
Product AS outerP
INNER JOIN
ProductPrice ON (outerP.prodType = ProductPrice.ProdType
AND outerP.Style = ProductPrice.Style)
GROUP BY outerP.prodType
order BY Profit DESC
LIMIT 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536641.html
下一篇:SQL中的父節點或葉節點
