tsql - 如何限制为 1 年期限
问题描述
此查询返回 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
我想要做的是返回最近 1 年的记录id
。
编辑@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
ofinserted
然后在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
推荐阅读
- android - 如何在android的进度条中设置进度
- javascript - 如何合并多维数组?
- sql - 通过 * 选择所有列和在 SQL 查询中指定所有列名来检索数据有什么区别?
- java - JPA 查询超时参数被忽略,但 @Transaction 注释有效
- r - 在 R 中的列表列表中的列上分配一个向量
- docker - 如何让 Docker 以 root 身份运行?
- codenameone - iOS 中的侧边菜单和选项卡问题 - cn1
- python - 从cleverhans攻击模型生成对抗数据
- php - 使用 PHP curl 对直接发布 API 进行发布调用时出现 Securepay Invalid Fingerprint 错误
- asp.net-mvc - 想要下载我们已上传以在文件签名上签名的确切文件格式