Sql - 计算库存天数

Sql - Calculate Inventory Days

我正在尝试计算一段时间内的库存天数。我在获取上个月的实际库存天数时遇到问题。所以对于第一行,9 天是正确的。但是第二行应该显示 34。因为我想计算 Inv_date 和“今天”日期之间的天数。假设我写这篇文章时,今天的日期是“2021-03-25”。

所以我有一个 table 例如:

Transdate Inv_Date Purch_Date InvDays
2021-02-01 00:00:00.000 20210219 Null 9
2021-03-01 00:00:00.000 20210219 Null 40

我期待的是:

Transdate Inv_Date Purch_Date InvDays
2021-02-01 00:00:00.000 20210219 Null 9
2021-03-01 00:00:00.000 20210219 Null 34

我的 Sql-InvdDays 计算脚本是:

case when left(Getdate(),8) >= left(convert(varchar,Transdate,112),8) then 
datediff(day,Inv_date,
dateadd(day,-1,dateadd(month,1,Transdate))
)
else 
isnull(ABS(DATEDIFF(day, Inv_date, isnull(Purch_Date, Getdate()))),0) end as InvDaysStandQty

嗯。 . .我推测您想要从 transdateinv_date 的最后一天算起的天数。那将是这样的:

select datediff(day, inv_date,
                (case when convert(date, getdate()) < eomonth(transdate)
                      then getdate() else eomonth(transdate)
                 end)
                )

可能会出现差1错误,因为你没有真正解释逻辑。