我有一个SQL表https://pasteboard.co/IfFt5rF.png,其中有成千上万条关于产品流量的记录,如果产品售出,数量为负,购买时为正。product_id是每个产品的唯一标识符。我想输入日期,并找出该日期之间的每个月,当它是零库存。
我在想,首先计算每个月的起始余额,只需找出过去期间的总和,然后逐行添加新数据,如果它得到零,那么它就是一个日期,但这种逻辑似乎超级可怕,甚至不知道如何在SQL中处理它。
我使用Microsoft SQL 2014
declare @Table table (general_id bigint, date datetime, product_id bigint, quantity float,
price float, code nvarchar(max), name nvarchar(max), partnumber nvarchar(max),
description nvarchar(max), rate float, comment nvarchar(max), currency nvarchar(max), waybill nvarchar(max))
insert into @Table (general_id, date, product_id, quantity, price, code, name, partnumber, description, rate, comment, currency, waybill)
select 1, '2019-03-1 16:33:00', 1, 10, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 2, '2019-03-2 16:33:09', 1, -5, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 3, '2019-03-3 16:33:12', 1, -3, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 4, '2019-03-4 16:39:00', 1, -2, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 5, '2019-03-4 16:39:41', 2, 40, 100, 102020, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 6, '2019-03-5 16:39:00', 2, -40, 100, 202020, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
union all
select 7, '2019-03-6 16:39:00', 1, 25, 100, 101010, 'test', 'testnumber', 'testdescription', 1.0, 'testcomment', 'USD', 'nobill'
SELECT DISTINCT product_id, code, name, partnumber, SUM(quantity)
FROM @TABLE
GROUP BY product_id, code, name, partnumber
ORDER BY product_id ASC 如果输入的日期范围是2019-03-01到2019-03-31,则当前案例的输出将为。product_id: 1 out_of_Stock_date: 2019-03-4 zero_stock_days: 2因为在2019-03-6购买了商品并且已经有库存
product_id: 2 out_of_stock_date: 2019-03-5 zero_stock_days: 26因为再也没人买过
发布于 2019-05-21 13:21:24
使用Sql Server >2008中提供的窗口函数尝试此查询:)
SELECT [lagDate] outOfStockStart,
[date] outOfStockEnd,
product_id,
daysOutOfStock
FROM (
SELECT *,
CASE WHEN LAG(stock) OVER (PARTITION BY product_id ORDER BY [date]) = 0 AND stock > 0 THEN
DATEDIFF(day, lagDate, [date]) ELSE NULL END daysOutOfStock
FROM (
SELECT [date],
LAG([date]) OVER (PARTITION BY product_id ORDER BY [date]) lagDate,
product_id,
SUM(quantity) over (PARTITION BY product_id ORDER BY [date]) stock
FROM @TABLE
) a
) a WHERE daysOutOfStock IS NOT NULLhttps://stackoverflow.com/questions/56230854
复制相似问题