Tsql 如何将期限限制为1年

Tsql 如何将期限限制为1年,tsql,sql-server-2012,having,Tsql,Sql Server 2012,Having,此查询返回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

此查询返回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.

使用子查询查找插入的
max
,然后在
中使用它

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

将所需条件添加到
WHERE
子句中。不具有
。如果不需要任何聚合函数,为什么要使用
groupby
。我已经在帖子中添加了更改后的查询。这会产生注意到的错误。