T-SQL - 使用相关子查询的聚合来聚合所有行
store item datekey onhand salesunits
--------------------------------------------
001 A 50 65 2
001 A 51 8 4
001 A 52 0 8
--------------------------------------------
我需要完成的任务是:按商店和商品获取大于零减去已售总单位数的最新库存。所以在上面的例子中它将是 8-14=-6。
我使用相关子查询来确定最新的日期键,然后连接回主查询。但显然这样做我会丢失与销售单位求和所需的其他行相关的数据:
这就是我所拥有的,这是错误的:
select s1.Store, s1.Item, s1.OnHand, sum(salesunit)
from sales s1
join (select top 1 store,item, max(DateKey) as datekey
from sales
where isnull(onhand,0) > 0
and DateKey in (50,51,52)
group by store, item) s2 on s2.store=s1.store and s2.item=s1.item and s2.datekey=s1.datekey
group by s1.Store, s1.Item, s1.OnHand
感谢您的帮助!
store item datekey onhand salesunits
--------------------------------------------
001 A 50 65 2
001 A 51 8 4
001 A 52 0 8
--------------------------------------------
What I need to accomplish: to get the latest onhand greater than zero minus the total units sold, by store and item. So in the example above it would be 8-14=-6.
I am using a correlated sub-query to determine the latest datekey and then joining back to the main query. But obviously by doing so I lose the data related to the other rows necessary to sum the salesunits:
This is what I have and it's wrong:
select s1.Store, s1.Item, s1.OnHand, sum(salesunit)
from sales s1
join (select top 1 store,item, max(DateKey) as datekey
from sales
where isnull(onhand,0) > 0
and DateKey in (50,51,52)
group by store, item) s2 on s2.store=s1.store and s2.item=s1.item and s2.datekey=s1.datekey
group by s1.Store, s1.Item, s1.OnHand
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会这样做:
首先一些测试数据:
查询如下:
I would do it something like this:
First some test data:
The the query like this: