如何获得每个供应商销售最高的产品?
到目前为止,我想到了这个,似乎无法继续进行。
select vendor.Vendor_Name, Product.category AS Product
, SUM(SalesFacts.Price * SalesFacts.Quantity) AS [Total Revenue]
FROM Vendor, Product, SalesFacts
WHERE SalesFacts.Vendor_Key = Vendor.Vendor_Key
AND SalesFacts.Product_Key = Product.Product_Key
GROUP BY vendor.Vendor_Name, product.Category
ORDER BY [Total Revenue] DESC;
(Product_Key和Vendor_Key是外键)
答案 0 :(得分:0)
select vendor.Vendor_Name,Product.category AS Product,
MAX(SalesFacts.Price * SalesFacts.Quantity) OVER (PARTITION BY
SalesFacts.Vendor_Key,SalesFacts.Product_Key ORDER BY SalesFacts.Vendor_Key ) AS
[Total Revenue] FROM Vendor
,Product,SalesFacts WHERE SalesFacts.Vendor_Key = Vendor.Vendor_Key AND
SalesFacts.Product_Key = Product.Product_Key
--GROUP BY vendor.Vendor_Name,product.Category,SalesFacts.Price,SalesFacts.Quantity
ORDER BY [Total Revenue] DESC;
答案 1 :(得分:0)
您可以使用它。
SELECT * FROM (
SELECT
vendor.Vendor_Name,
Product.Category AS Product,
ROW_NUMBER() OVER(PARTITION BY vendor.Vendor_Name ORDER BY SUM(SalesFacts.Price * SalesFacts.Quantity) DESC) RN
FROM Vendor
INNER JOIN SalesFacts ON SalesFacts.Vendor_Key = Vendor.Vendor_Key
INNER JOIN Product ON SalesFacts.Product_Key = Product.Product_Key
GROUP BY vendor.Vendor_Name, product.Category
) X
WHERE X.RN = 1
答案 2 :(得分:0)
我不明白为什么“类别”应该是产品。更重要的是,您应该修复查询:
FROM
子句中使用逗号。JOIN
语法。在产品级别,这将是:
SELECT Vendor_Name, Product
FROM (SELECT v.Vendor_Name, p.Description AS Product,
ROW_NUMBER() OVER (PARTITION BY v.Vendor_Key ORDER BY SUM(sf.Price * sf.Quantity) DESC) as seqnum
FROM SalesFacts sf JOIN
Vendor v
ON sf.Vendor_Key = v.Vendor_Key JOIN
Product p
ON sf.Product_Key = p.Product_Key
GROUP BY v.Vendor_Key, v.Vendor_Name, p.Product_Key, p.Description
) vp
WHERE vp.seqnum = 1;
可以轻松地对其进行修改以适用于该类别,但是问题是“产品”,并且数据具有与此对应的内容。