首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SQL选择一行直到某个条件

SQL选择一行直到某个条件
EN

Stack Overflow用户
提问于 2014-01-24 08:01:52
回答 2查看 90关注 0票数 0

我有两个表,如下:

第一个表显示了所有订单:

代码语言:javascript
运行
复制
table PURCHASE_ORDER:
ID   UNIT_#    PRICE   ITEM_KEY
1      2         3        1
2      3         2.5      1
3      1         3        1

第二个表显示了库存中的可用数量:

代码语言:javascript
运行
复制
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中做到这一点?

EN

Stack Overflow用户

发布于 2014-01-24 08:20:51

你需要一个累加的总数。假设您使用的是SQL Server 2012,因为它简化了代码。

代码语言:javascript
运行
复制
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的早期版本中,需要对累积和使用相关子查询。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21321885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档