【问题标题】:How to find the earnings from the most sold product with sql?如何用sql查找销量最高的产品的收益?
【发布时间】:2021-12-21 16:05:14
【问题描述】:

我有两张桌子:

我需要找到销量最高的产品名称以及从中获得的收益。

我写的代码:

SELECT * 
FROM Products 
WHERE ProductId = (SELECT ProductId
                   FROM 
                       (SELECT 
                            ProductId, 
                            SUM(Quantity) AS total_order,
                            MAX(SUM(Quantity)) OVER () AS maxSm 
                        FROM
                            Orders
                        GROUP BY
                            ProductId)
                   WHERE 
                        total_order = maxSm)

但有了这个,我只能找到销量最高的产品名称。你能告诉我,我怎样才能找到这个产品的收入?

【问题讨论】:

标签: sql sqlite max product


【解决方案1】:
select top 1
    a.name,
    (b.total * a.price) as revenue
from
    products a
    left join (select productid, sum(quantity) as total group by productid) b
        on a.productid = b.productid
order by
    b.total desc

【讨论】:

    【解决方案2】:

    您需要将派生表的结果连接到您的Products 表中。

    没有实际的样本数据我无法测试,但是以下应该是您需要的,或者至少非常接近:

    select p.Name, o.total_order, o.total_order * p.Price as TotalValue
    from (
        select * from (
            select ProductId, 
                Sum(Quantity) as total_order, 
                Max(Sum(Quantity)) over () as maxSm 
            from Orders
            group byProductId
        )t
        where total_order = maxSm
    )o join Products p on p.ProductId=o.ProductId
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多