好的,这很奇怪,我将尽力解释我的意思。
比方说,我知道目前的sku库存:
select sku, sum(stock)
from stock
where sku = '1234'
group by sku
然后我得到该sku的销售额:
select *
from sales
where sku = '1234' and saleDate > SOME_DATE <---- Get sales for a certain period
order by saleDate desc
我想查找什么是库存水平,以及导致库存下降到给定日期的原因。
所以结果应该像这样:
Current stock @ 21.06.2019 is 50 <---- I know this value
20.06.2019: stockStart = 53, sold = 3, stockEnd = 50 <---- I know the sales, don't know the stock
19.06.2019: stockStart = 58, sold = 5, stockEnd = 53 <---- I know the sales, don't know the stock
18.06.2019: stockStart = 60, sold = 2, stockEnd = 58 <---- I know the sales, don't know the stock
17.06.2019: stockStart = 68, sold = 8, stockEnd = 60 <---- I know the sales, don't know the stock
Initial stock @ 16.06.2019 was 68 <---- Don't know this value
如何通过SQL查询获得类似的信息,我知道当前库存,知道出售了什么,但是我想找到:
答案 0 :(得分:0)
检查以下查询。某些内联和子查询可能会导致性能问题。但是考虑到您的要求,我认为以下查询将至少为您提供一些指导。
DECLARE @FromDate DATE = '20190619'
SELECT saleDate Date,
Current_Stock + ISNULL(sold_from_today,0) stockStart,
Sold,
Current_Stock + ISNULL(sold_from_tomorrow,0) stockEnd
FROM
(
Select *,
(select sku, sum(stock) from stock where sku = '1234') Current_Stock,
--68 Current_Stock,
(SELECT SUM(Sold) FROM sales B WHERE B.saleDate >= A.saleDate AND B.saleDate > @FromDate AND B.sku = '1234') sold_from_tomorrow,
(SELECT SUM(Sold) FROM sales B WHERE B.saleDate > A.saleDate AND B.saleDate > @FromDate AND B.sku = '1234') Usold_from_today
from sales A
where A.sku = '1234' and A.saleDate > @FromDate
)A
ORDER BY saleDate DESC