计算销售订单与饮料相同的所有销售订单的总销售额

时间:2016-04-28 06:35:51

标签: sql sql-server-2008

我正在尝试查询计算销售订单编号的总销售额,该查询等于饮料的销售订单编号。

这是我的查询,但它只给我饮料总销售额而不是所有其他具有相同销售订单的商品:

SELECT
SalesOrderNumber,TransactionDate,[ProductClass],[ProductName],  Nett
FROM ((([Sales]
inner join [Date]
on [Sales].DateKey = [Date].DateKey)
inner join [Product] on [Sales].ProductKey = [Product].ProductKey
inner join [ProductCategory] on [Product].ProductCategoryKey =[ProductCategory].ProductCategoryKey)
inner join [Store] on [Sales].StoreKey = [Store].StoreKey)
where  SalesOrderNumber in (select SalesOrderNumber from [Sales] where ProductClass = 'Beverages')
and StoreName = 'XYZ'
and [FullDate] = '2016-04-27'
ORDER BY SalesOrderNumber,TransactionDate

有人可以帮我解决上述问题吗?

实施例

Salesorder1: Beverages - 5$
             Chicken - 10$
Salesorder2: Chicken - 12$
             Chips - 8$

我只需要含有饮料的总和。因此,根据上面的示例,我应该(Beverages + Chicken = 15$),而不应该包含salesorder2

1 个答案:

答案 0 :(得分:0)

您的查询几乎无法辨认。考虑将来使用一些打算。

但是,由于您需要包含多个产品总和的行,因此无法在同一行中选择[ProductClass]和[ProductName]之类的内容。你必须将它们归为像SalesOrderNumber这样常见的东西。

如果以下查询无效,则完全不确定,但只有我更改的内容是查询的第一行和最后一行。

SELECT SalesOrderNumber,TransactionDate, SUM(Nett) as sum
FROM 
(
  (
    ([Sales] inner join [Date] on [Sales].DateKey = [Date].DateKey)
  inner join [Product] on [Sales].ProductKey = [Product].ProductKey
  inner join [ProductCategory] on [Product].ProductCategoryKey = [ProductCategory].ProductCategoryKey
  )
inner join [Store] on [Sales].StoreKey = [Store].StoreKey
) 
where SalesOrderNumber in 
  (select SalesOrderNumber from [Sales] where ProductClass = 'Beverages') 
  and StoreName = 'XYZ'
  and [FullDate] = '2016-04-27'
GROUP BY SalesOrderNumber, TransactionDate