【问题标题】:Select rows from a table where a timestamp has not been made since the past 60 days从过去 60 天内未创建时间戳的表中选择行
【发布时间】:2016-05-27 14:50:26
【问题描述】:

我正在使用 sql server 2012 在 sql managment studio 中开展一个项目,我想获得一个包含过去 60 天内未进行交易的用户编号的列表。数据来自 2 个表(用户和事务),其中一个表保存用户编号和用户 ID,另一表保存事务时间戳和用户 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

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

【问题讨论】:

    标签: sql sql-server transactions timestamp


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 如果我希望用户在过去 30 天内有交易,这种方法是否也适用?有 max(b.timestamp) >= (SELECT getdate()-30)?
    • @Glews 是的,只需选择您需要的任何日期偏移量
    【解决方案2】:

    无需在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
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 2020-03-21
      • 2013-02-09
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多