【问题标题】:How to restrict to 1 year period如何限制为 1 年期限
【发布时间】:2021-07-15 06:35:29
【问题描述】:

此查询返回 3 年的记录。如何将其更改为返回(最近的)1 年的记录?

select id, format(ual.inserted, 'yyyy-MM-dd') as inserted
from ual
where id = 347877
group by id, format(ual.inserted, 'yyyy-MM-dd')
having format(ual.inserted, 'yyyy-MM-dd') >= dateadd(year,-1,max(inserted))
order by format(ual.inserted, 'yyyy-MM-dd') desc

我要做的是返回每个id 的最近 1 年的记录。

编辑在@Squirrel 发表评论后所做的更改:

select id, format(ual.inserted, 'yyyy-MM-dd') as inserted
from ual
where webid = 347877 and format(ual.inserted, 'yyyy-MM-dd') >= dateadd(year,-1,max(inserted))
order by format(ual.inserted, 'yyyy-MM-dd') desc

此查询产生此错误:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

【问题讨论】:

  • 将所需条件添加到WHERE 子句。不是HAVING。以及为什么在不需要任何聚合函数的情况下使用GROUP BY
  • 我已将更改后的查询添加到帖子中。这会产生注意到的错误。

标签: tsql sql-server-2012 having


【解决方案1】:

使用子查询找到insertedmax,然后在where中使用

select id, format(ual.inserted, 'yyyy-MM-dd') as inserted
from   ual
where id = 347877
and   ual.inserted >= (
                          select dateadd(year,-1,max(inserted))
                          from   ual x
                          where  x.id = ual.id
                      )
order by format(ual.inserted, 'yyyy-MM-dd') desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2015-10-03
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    相关资源
    最近更新 更多