试图在SQL中查找SUM查询的MAX值

时间:2018-02-16 20:26:19

标签: sql join sum max teradata

我有两张桌子:

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功能仅显示列表的最高值?我无法使用LIMITTOP进行此分配,但每当我使用MAX时,我都会遇到有关聚合的各种问题。

完成后,如何显示最畅销产品的产品名称?

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试一下:

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) 

如果两个表中都有匹配的行,则只返回行。

答案 1 :(得分:0)

这有点简单,但我认为这仍然适合你

select productid, max(itemsum) 
from
(SELECT productid, sum(noofitems) as itemsum
FROM soldvia
group by productid)
; 

答案 2 :(得分:0)

根据@ ravioli的回答,没有子选择。

从逻辑上我更喜欢subselect(早期减少行数),但解释显示,subselect使用了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
;