我正在处理包含这两个表的查询: 表A:
Store NumItems
1 500
2 1000
3 575
表B:
Store Day ItemsSold
1 Monday 100
1 Tuesday 200
1 Wednesday 110
1 Thursday 10
1 Friday 1
1 Saturday 140
1 Sunday 90
2 Monday 400
2 Tuesday 150
2 Wednesday 501
2 Thursday 190
2 Friday 600
2 Saturday 180
2 Sunday 21
3 Monday 100
3 Tuesday 1050
3 Wednesday 108
3 Thursday 102
3 Friday 51
3 Saturday 40
3 Sunday 15
我需要知道商店什么时候用完了。我可以得到我运行的过程的一周的日期,但我需要循环或以某种方式继续从每个商店和庄园中减去(假设这是在星期一运行 - 商店1将在星期六的商店1上的商品用完,商店2将在周三用完,商店3将在周二用完。
提前谢谢大家的帮助!!!
答案 0 :(得分:1)
你可以试试这个。
写CTE来计算每天累积的差异量。然后获得查询中获得最大的负数。
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() .
'/style.css' );
}
sqlfiddle:http://sqlfiddle.com/#!18/2a472/1
答案 1 :(得分:0)
假设支持sum
窗口功能,您可以
select top 1 with ties store,day
from (select a.store,b.day,
a.numItems-sum(b.itemsSold) over(partition by b.store
order by case when b.day='Monday' then 1
when b.day='Tuesday' then 2
--/*fill remaining values*/...
end
) as rem
from tblA a
join tblB b on a.store=b.store
) t
where rem <= 0
order by row_number() over(partition by store order by rem desc)
我们的想法是从day
顺序的总项中减去itemsSold的运行总数,并得到第一行,其差异为<= 0。
答案 2 :(得分:0)
您只需要一笔累计金额:
select b.*
from a join
(select b.*,
sum(itemsold) over (partition by store order by date) as running_itemssold
from b
) b
on a.store = b.store
where a.numitems > b.running_itemssold - itemsold and
a.numitems <= b.running_itemsold;
这计算出当物品数量为零时的售罄。如果您确实需要缩短项目,则需要更改条件,以使第二个条件为<
而不是<=
。