[英]Trying to Find MAX value of a SUM query in SQL
我有2張桌子:
Product(ProductID, ProductName, ProductPrice, VendorID, CategoryID)
SoldVia(ProductID, TID, NoOfItems)
我需要顯示已售出最大數量產品的productID。 通過此查詢,我可以輕松得出按升序排序的列表:
SELECT distinct productid, sum(noofitems)
From soldvia
Group By productid
Order By sum(noofitems) DESC
問題是,如何使用MAX
函數僅顯示列表的最高值? 我不能使用LIMIT
或TOP
進行此分配,但是每當使用MAX
,都會遇到聚合問題。
完成后,如何顯示最暢銷產品的產品名稱?
謝謝!
試試看:
SELECT prd.ProductId
FROM Product prd
INNER JOIN SoldVia sld ON prd.ProductId = sld.ProductId
WHERE prd.NoOfItems = (SELECT MAX(NoOfItems) FROM SoldVia) -- Check for item that has max # items sold
這將返回NoOfItems
合計值最高的項目
更新
我不知道您在使用Teradata。 這使生活容易得多:)
SELECT ProductName
FROM Product prd
INNER JOIN (
SELECT ProductId, SUM(NoOfItems) AS TotalItemsSold
FROM SoldVia
GROUP BY ProductId
QUALIFY RANK() OVER(ORDER BY TotalItemsSold DESC) = 1 -- Only return ProductId(s) with largest TotalItemsSold value (includes ties)
) agg ON prd.ProductId = agg.ProductId -- Get aggregate # items sold (if any)
如果兩個表中都有匹配的行,則只會返回行。
這有點簡單,但是我認為這仍然應該為您工作
select productid, max(itemsum)
from
(SELECT productid, sum(noofitems) as itemsum
FROM soldvia
group by productid)
;
基於@ravioli的答案,沒有子選擇。
從邏輯上講,我更喜歡子選擇(盡早減少行數),但是解釋顯示,子選擇又使用了1個步驟。 我希望對於更多行它會有所不同。
select
S.ProductID
, P.ProductName
, sum(NoOfItems) as TotalItemsSold
from SoldVia as S
inner join Product as P
on S.ProductID = P.ProductID
group by S.ProductID, P.ProductName
QUALIFY RANK() OVER(ORDER BY TotalItemsSold DESC) = 1 -- Only return ProductId(s) with largest TotalItemsSold
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.