【问题标题】:How to get total sales for each product in Order Details table in Northwind database in a single statement?如何在单个语句中获取 Northwind 数据库中订单详细信息表中每个产品的总销售额?
【发布时间】:2014-07-06 23:39:33
【问题描述】:

如何在一条语句中获取 Northwind 数据库中 Order Details 表中每个产品的总销售额?

我知道该怎么做:

select productid,  UnitPrice * (1 - Discount) * sum(Quantity) 
  from [Order Details]
    group by ProductID,UnitPrice, Discount

我为每个 productid 获取了多行,然后我可以运行另一个查询来为每个 productid 获取一个总和。 请注意,同一产品 ID 的折扣可能不同

我想在一条 SQL 语句中完成所有操作。怎么样?

【问题讨论】:

  • 只使用group by ProductID
  • 不起作用。 UnitPrice 和 Discount 必须是聚合函数或在一个组中
  • 你可能想要:sum(UnitPrice * (1 - Discount) * Quantity)

标签: sql sql-server select sum


【解决方案1】:

您可以只提取您的 sum 函数来单独对每一行的价格求和,而不是仅仅对数量求和(这在数学上应该没问题,因为 distributive property 的乘法超过加法):

SELECT   productid,  SUM(UnitPrice * (1 - Discount) * Quantity)
FROM     [Order Details]
GROUP BY ProductID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多