【问题标题】:TSQL - Compare two columns with self join - Calculate the difference between yesterdays total's and today's totalTSQL - 使用自连接比较两列 - 计算昨天总计和今天总计之间的差异
【发布时间】:2020-12-04 13:42:23
【问题描述】:

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

要求:

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

问题

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

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


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))

【问题讨论】:

  • 旁白:将datetime 用于date 值可能会有问题。除了午夜之外,您实际上还有其他时间值吗?
  • @HABO,是的,在某些情况下,我想知道它发生在什么时间,以确保它发生在另一个过程之后。

标签: sql tsql sql-server-2014


【解决方案1】:

我想你想要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;

注意:这将“昨天”解释为表格中的最后两天。如果你真的想要今天和昨天,那么你可以使用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;

【讨论】:

  • 谢谢@GordonLinoff。当我将我的 empcount 更改为 INT 时,这有效。感谢您的帮助!
猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2021-11-25
  • 2010-12-09
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多