获得每个供应商销售最高的产品

时间:2019-10-19 07:25:12

标签: sql sql-server

如何获得每个供应商销售最高的产品?

到目前为止,我想到了这个,似乎无法继续进行。

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;

Vendor Table

Product Table

Sales Table

(Product_Key和Vendor_Key是外键)

3 个答案:

答案 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;

可以轻松地对其进行修改以适用于该类别,但是问题是“产品”,并且数据具有与此对应的内容。