来自 table 的 Select 行,其中自过去 60 天以来未创建时间戳

Select rows from a table where a timestamp has not been made since the past 60 days

我正在 sql managment studio 中使用 sql 服务器 2012 进行一个项目,我想获得一个列表,其中包含上次未进行交易的用户编号60天。数据来自 2 tables(用户和交易),其中一个 table 保存用户编号和用户 ID,另一个 table 保存交易时间戳和用户 ID。我现在的解决方案是:

SELECT a.usernumber
FROM [user] a left join [transaction] b on a.id = b.user_id 
WHERE b.timestamp <= (SELECT getdate()-60) and a.usernumber is not null

问题是现在它会 return 所有在 60 天前进行过交易的用户,但他们也可以在最近 60 天内进行过交易。那么这个问题有什么好的解决方案呢?

您可以按 usernumber 对结果进行分组,仅计算 max(b.timestamp) 和 select 具有在您所需日期之前的最新时间戳的记录:

select a.usernumber
from [user] a 
    left join [transaction] b on a.id = b.user_id 
where a.usernumber is not null
group by a.usernumber
having max(b.timestamp) <= (SELECT getdate()-60)

不需要在 getdate() 调用前加上 select。但是最好计算不依赖于 select 语句之前每一行的参数。您的目标可以用其他词来定义:显示没有超过 60 天的交易的用户。

让我们直接将其翻译成 sql 语句:

declare @oldestdate datetime

set @oldestdate = dateadd(dd, -60, getdate())

select u.username
from [user] u
where not exists
  (
    select 1 
    from [transaction] t
    where t.user_id = u.user_id
      and t.timestamp > @oldestdate
  )