2014-01-24 39 views
0

我有两个表如下:SQL选择行直到条件

第一个表显示所有订单:

table PURCHASE_ORDER: 
ID UNIT_# PRICE ITEM_KEY 
1  2   3  1 
2  3   2.5  1 
3  1   3  1 

第二个表显示在清单的单位可用数量:

table INVENTORY: 
ID ITEM_KEY UNIT_AVAILABLE 
1  1   5 
2  2   7 

现在的问题是如何计算库存中物料的平均成本。例如对于项目1:

项目1的平均成本=((1 * 3)+(3 * 2.5)+(1 * 3))/ 5
/*库存中项目的总数是5(1 + 3 + 1 = 5)*/

是否有任何方法可以在纯Microsoft SQL中执行此操作?

+0

什么是Unit_#?这是你以这个价格购买的单位数量吗? – 2014-01-24 00:06:54

+0

是的,这正是它是 – kousha

+0

是的,它可以做到。你介意在这里解释每个号码的列名吗? ((1 * 3)+(3 * 2.5)+(1 * 3))/ 5 ...谢谢...像第一个1是Item_Key或其他 –

回答

1

您需要一个累计和。让我假设您正在使用SQL Server 2012,因为它简化了代码。

select po.item_key, 
     (sum(case when po.cumunits <= i.unit_available then po.[unit#]*po.price 
       when po.cumunits > i.unit_available and 
         po.cumunits - [unit#] < i.unit_available 
       then (i.unit_available - (po.cumunits - [unit#]))*po.price 
       else 0 
      end)/
     sum(case when po.cumunits <= i.unit_available then po.[unit#] 
       when po.cumunits > i.unit_available and 
         po.cumunits - [unit#] < i.unit_available 
       then (i.unit_available - (po.cumunits - [unit#])) 
       else 0 
      end) 
    ) as avgprice 
from (select po.*, sum([unit#]) over (partition by item_key order by id) as cumunits 
     from purchase_order po 
    ) po join 
    inventory i 
    on po.item_key = i.item_key 
group po.item_key; 

在早期版本的SQL Server中,您需要使用相关子查询作为累计和。

+0

这看起来是我想要的。我会尝试并让你知道。 – kousha

+0

这一个没有工作,我想我会用一些其他非数据导向的语言来做到这一点 – kousha

0

基于表如何设置

select po.* 
    , i.* 
    , AvgPrice = sum(po.[UNIT_#] * po.Price) over (partition by po.item_key) 
       /
        i.unit_available 
    from PURCHASE_ORDER po 
     inner join INVENTORY i 
     on (po.ITEM_KEY = i.ITEM_KEY); 

应该做的伎俩