【问题标题】:greater than a certain number sql [duplicate]大于一定数量的sql [重复]
【发布时间】:2013-03-25 00:05:12
【问题描述】:

我需要进行一个 sql 查询,它将显示以下内容:

'截至当前日期超过 90 天的活跃帐户总数'

日期来自一个 sql 查询,它是这样的:

select date from currentdatetable

现在我的查询是计算来自 accounttable 的所有活动帐户,因此我的查询如下所示:

select count(*) from accountstable

我的问题是如何声明 accounttable 中的日期比 currentdatetable 的日期早 90 天?

我当前的代码:

select count(*) from accountstable at where at.date > (select date from currentdatetable)

【问题讨论】:

  • 你使用的是什么 rdbms?
  • 微软 sql server 2005
  • 只是好奇,为什么你有一个带有当前日期的表?而且里面只有一条记录吗?
  • 它不是系统日期。日期取决于它所在的数据库

标签: sql sql-server-2005 date select count


【解决方案1】:
select count(*) from accountstable at where at.date > (select dateadd(day, -90,date) from currentdatetable)

【讨论】:

  • DATEADD 的参数顺序错误 - count(*) from accounttable at where at.date
  • 抱歉,已经修复
  • 嗨,安迪,为什么是你的 对吧?因为我们正在寻找大于日期的帐户?
  • 又是我的错 - 我误解了原始请求并进行了编辑
【解决方案2】:

使用 MS SQL-Server,您可以使用 DATEADD + DATEDIFF:

SELECT Count = Count(*),
       Date = (SELECT TOP 1 [date] 
               FROM   currentdatetable)
FROM   accountstable a 
WHERE  Datediff(dd, a.[date], (SELECT TOP 1 [date] 
                               FROM   currentdatetable)) > 90 

Demo

【讨论】:

    【解决方案3】:

    您可以只选择更大的日期来优化上层答案:

    select count(*) from accounttable at where at.date > (select TOP 1 dateadd(day, -90,date) from currentdatetable ORDER BY date DESC)

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2017-01-25
      相关资源
      最近更新 更多