TSQL - 使用自连接比较两列 - 计算昨天总计和今天总计之间的差异

TSQL - Compare two columns with self join - Calculate the difference between yesterdays total's and today's total

我正在尝试计算列上今天和昨天总计之间的差异。如果自连接不是最好的方式,那也没关系,无论哪个能给我我想要的结果都应该没问题。

要求:

  1. 只比较最近 2 天的数据,即使 table 会有多天的数据,但每天只有一个条目。
  2. 计算该列昨天总计和今天总计之间的差值。

问题

下面的代码 returns 是一个零,我不明白为什么。

为什么计算不出来,请问我应该怎么做才能满足要求?


IF OBJECT_ID('tempdb..#t1') IS NOT NULL DROP TABLE #t1

CREATE TABLE #t1 (
 countID UNIQUEIDENTIFIER
,empCount VARCHAR(20)
,CountDate DATETIME
)

INSERT INTO #t1 (
    countID
  , empCount
  , CountDate
)
VALUES
     (NEWID(),'123000', GETDATE()) 
    ,(NEWID(),'100', '20200813')
    ,(NEWID(),'100', '20200810')

SELECT 
    today.countID
  , (CAST(today.empCount AS INT)) - (CAST(yesterday.empCount AS INT)) AS CountDiff
  , today.empCount
  , today.CountDate
FROM #t1 AS today
INNER JOIN #t1 AS yesterday ON today.countID = yesterday.countID
                                AND yesterday.CountDate > (SELECT dateadd(day,datediff(day,2,GETDATE()),0))

我想你想要 lag():

select t.*,
       (empcount - lag(empcount) over (order by countdate)) as diff
from #t1 t;

如果您只想要最后两天,那么:

select top (1) t.*
from (select t.*,
             (empcount - lag(empcount) over (order by countdate)) as diff
      from #t1 t
     ) t
order by countdate desc;

注意:这会将“昨天”解释为 table 中的最后两天。如果你真的想要今天和昨天,那么你可以使用 where 子句:

select top (1) t.*
from (select t.*,
             (empcount - lag(empcount) over (order by countdate)) as diff
      from #t1 t
      where countdate >= dateadd(day, -1, convert(date, getdate()))
     ) t
order by countdate desc;