如何找到两个日期之间的差异?计算找到两个计数之间的差异?

时间:2018-03-16 07:19:21

标签: sql tsql stored-procedures sql-server-2012

DATE               Item              Count   
------------------------------------------
2018-03-15         Basketball        1000
2018-03-12         Basketball         950
2018-03-07         Basketball         900
2018-03-02         Basketball         850

上面的这些行属于表中的不同行位置,它们的排序方式类似于使用下面和下面的查询查询都在存储过程中。

我想要做的是找到计数差异的数量和两个日期之间的天数差异

select Top 1  Date, Item, Count 
from SportsItemSells 
where @Item ='BasketBall' 
order by DATE desc   -- returns first row

select Date, ITEM, Count 
from SportsItemsSells 
where @Item =Item
order by DATE desc
      offset 1 rows 
      fetch next 1 row only;   -- returns second row

Select Date, ITEM, Count 
from SportsItemsSells 
where @Item =Item
order by DATE desc
      offset 2 rows 
      fetch next 1 row only;   -- returns third row

当我尝试计算存储过程中两个日期之间的天差时,它总是返回零

@DayDifferenceCalculation1 = DateDIFF( day,@Date,@Date)

我想要的是DateDiff(Day,@DateRow1,@DateRow2)但是如何动态定义不同日期和不同行的日期?

@CountDifferenceCalculation1 = @Count - @Count (

无论如何,它总是会返回零。

我想要的是

 @CountDifferenceCalculation1 = @Count1 - @Count2 )

但所有这些计数都设置为@Count,日期设置为@Date如何为不同的行定义@Date@Count

任何帮助将不胜感激

enter image description here

2 个答案:

答案 0 :(得分:0)

这是你需要的吗?

SELECT  Item,
        Date,
        LEAD(Date,1,null) OVER (ORDER BY Date) AS NextDate,
        DATEDIFF(day,[Date],LEAD(Date,1,null) OVER (ORDER BY Date)) AS DateDifference,
        Count,
        Count-LEAD(Count,1,null) OVER (ORDER BY Date) AS CountDifference

FROM #Temp1

结果将是

enter image description here

答案 1 :(得分:0)

尝试以下代码

WITH CTE_SportsItemSells AS
(
select  Date,Item,Count,ROW_NUMBER() OVER (ORDER BY Date DESC) Rn
from SportsItemSells 
WHERE Item='Basketball'
)
SELECT C.DATE AS MostRecentDate
,C2.Date AS NextDates 
,C.Item AS RecentCount
,C2.COUNT AS NextCounts
,DATEDIFF(DAY,C.Date,C2.Date) AS DateDifference
,C.Count-C2.Count AS 'CountDifference'
FROM CTE_SportsItemSells AS C
LEFT JOIN CTE_SportsItemSells AS C2 ON C.Rn<C2.Rn
WHERE C.Rn=1 AND C2.Rn<=4