我有看起来像这样的数据。SQL查找n行的平均值,其中n是字段的总和
SoldToRetailer
OrderDate | Customer | Product | price | units
-------------------------------------------------
1-jun-2011 | customer1 | Product1 | $10 | 5
2-jun-2011 | customer1 | Product1 | $5 | 3
3-jun-2011 | customer1 | Product2 | $10 | 4
4-jun-2011 | customer1 | Product1 | $4 | 4
5-jun-2011 | customer2 | Product3 | $10 | 1
SalesByRetailers
Customer | Product | units
-----------------------------
customer1 | Product1 | 5
customer2 | Product3 | 1
这是我所需要的。
销售(平均价格)
Customer | Product | units | Average Price
--------------------------------------------
customer1 | Product1 | 5 | $3.44
customer2 | Product3 | 1 | $10
平均价格被定义为平均价格最近SoldToRetailer价格加起来的单位。
因此,在第一种情况下,我从6月4日和6月2日获取订单。我不需要(实际上需要)从6月1日起的订单被包括在内。
编辑:希望更好的解释。
我试图确定一个项目被卖给零售商的正确(最近的)价格。这是价格的LIFO订单。价格是通过平均最近n次订单的价格来确定的。其中n =特定产品和客户的零售总额。
在SQL伪代码看起来像这样。
Select s1.Customer, s1.product, average(s2.price)
from SalesByRetailers s1
join SoldToRetailer s2
on s1.customer=s2.customer
and s1.product=s2.product
and (select top (count of records where s2.units = s1.units) from s2 order by OrderDate desc)
我需要返回的是来自SoldToRetailer的记录数量,其中单位总和> = SalesByRetailer单位。
它看起来可以通过RANK或rowover分区来解决,但我很茫然。
SoldToRetailer表格是巨大的,所以性能是非常宝贵的。
运行在SQL 2008R2 感谢您的帮助
“product1总订单为9”从哪里来?单位卖出,单位库存?什么是期望的输出?为什么没有2011年1月1日的product1数据?这不是太清楚... – gbn
编辑以提高清晰度。 9是单位总价和单位库存。期望的产出是客户,产品,平均价格。详细信息记录日期,因此只返回最近的记录。 –
你如何达到平均价格3.44?为什么你有客户和订单的单位? –