简体   繁体   English

Sql - 计算库存天数

[英]Sql - Calculate Inventory Days

I'm trying to calculate inventory day's over time.我正在尝试计算一段时间内的库存天数。 I have an issue getting the actual amount of day's in inventory for the last month.我在获取上个月库存的实际天数时遇到问题。 So as for the first row, the 9 days is correct.所以对于第一行,9 天是正确的。 However the second row should show 34. Since I want to calculate the days between Inv_date and "today's" Date.但是第二行应该显示 34。因为我想计算 Inv_date 和“今天的”日期之间的天数。 Let's presume when I'm writing this, today's date is '2021-03-25'.假设我在写这篇文章时,今天的日期是“2021-03-25”。

So I have a table such as:所以我有一张桌子,例如:

Transdate翻译 Inv_Date Inv_Date Purch_Date采购日期 InvDays发票天数
2021-02-01 00:00:00.000 2021-02-01 00:00:00.000 20210219 20210219 Null Null 9 9
2021-03-01 00:00:00.000 2021-03-01 00:00:00.000 20210219 20210219 Null Null 40 40

What I'm expecting is:我期待的是:

Transdate翻译 Inv_Date Inv_Date Purch_Date采购日期 InvDays发票天数
2021-02-01 00:00:00.000 2021-02-01 00:00:00.000 20210219 20210219 Null Null 9 9
2021-03-01 00:00:00.000 2021-03-01 00:00:00.000 20210219 20210219 Null Null 34 34

My Sql-script for the InvdDays calculation is:我用于 InvdDays 计算的 Sql 脚本是:

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

Hmmm.嗯。 . . . . I speculate that you want the number of days from the last day of transdate and inv_date .我推测您想要从transdateinv_date的最后一天开始的天数。 That would be something like this:那将是这样的:

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

There might be an off-by-1 error, because you haven't actually explained the logic.可能有一个 off-by-1 错误,因为您实际上还没有解释逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM