在T-SQL中查找天数的差异

时间:2016-08-06 18:07:38

标签: sql-server tsql

我的表格详情是:

Date                ORGUnitCode SKUId   LocationID  LP  DivisionCode    DeptCode    CategoryCode    OPBalQty    OPBalValue  Sync    
2013-03-31 00:00:00 DELG14  10059764    107       432.55    G           MN          KLO             0.00            0.00    0   
2013-03-31 00:00:00 DELG14  10063213    107       699.05    G           MN          KLO             0.00            0.00    0   
2013-03-31 00:00:00 DELG14  10090728    107       250.76    G           MN          PYJ             0.00            0.00    0   

此处OPBalQty在大量记录中 1.00 0.00

我想知道所有可用OPBalQty的{​​{1}} 0.00 以来的天数,将其重新定义为特定的skuId,即该数字的stockOut的日子。我试图找到它,但没有工作可以任何人指向这个?

2 个答案:

答案 0 :(得分:0)

根据您的最新评论,我相信这是您正在寻找的答案。希望您可以看到这些是同一主题的变体,您可以根据需要进行调整。

select
    SKUId,
    datediff(
        day,
        max(case when OPBalQty = 1 then "Date" end),
        max(case when OPBalQty = 0 then "Date" end)
    ) as NumDays

from T
group by SKUId
having max(case when OPBalQty = 0 then "Date" end) = max("Date")

上一个答案

如果您只想获得零OPBalQty的最新日期,那么您只需查找可用于差异计算的max()日期。

select
    SKUId,
    datediff(day, getdate(), max("Date")) as NumDays
from T
where OPBalQty = 0
group by SKUId

如果您只查找最新日期为零的SKU,则可以在having条款中使用各种检查。

select
    SKUId,
    datediff(day, getdate(), max("Date") as NumDays
from T
group by SKUId
having max(case when OPBalQty = 0 then "Date" end) = max("Date")
-- this condition would also work if it seems clearer
-- max(case when OPBalQty=0 then "Date" end) > max(case when OPBalQty=1 then "Date" end)

当然,如果您只需要查看日期差异大于某些天数的SKU,那么只需将该条件添加到having

select
    SKUId,
    datediff(day, getdate(), max("Date")) as NumDays
from T
group by SKUId
having  max(case when OPBalQty = 0 then "Date" end) = max("Date")
    and datediff(day, getdate(), max("Date")) >= X

答案 1 :(得分:0)

对所讨论问题的指出解决方案:

select distinct SKUId,
        datediff( day,
        max(case when OPBalQty > 0 then "Date" end),
        max(case when OPBalQty = 0 then "Date" when OPBalQty = -1 then "Date" end)) as NumDays
    from Admin.Stocks
    group by SKUId
    having max(case when OPBalQty = 0 then "Date" end) = max("Date")