在列列表中使用子查询
我想创建一个查询来计算过去 7 天、14 天和 28 天创建的记录数。我的结果将返回类似以下内容的内容:
7Days 14Days 28Days
21 35 56
我知道如何在每个时间(例如 7 天)内执行此操作,但我是否可以在一个查询中捕获所有三个?
select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days. My result would return something like:
7Days 14Days 28Days
21 35 56
I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?
select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也不漂亮,但不依赖子查询(表/列名称来自 AdventureWorks)。如果 case 语句符合您的条件,则返回 1,否则返回 0 - 那么您只需对结果求和:
编辑: 更新了 datediff 函数 - 按照其编写方式,它将返回负数(假设moddeddate 是过去的)导致所有项目都属于第一种情况。感谢 Andriy M 指出了这一点
Also not pretty, but doesn't rely on subqueries (table/column names are from AdventureWorks). The case statement returns 1 if it falls within your criteria, 0 otherwise - then you just sum the results :
Edit: Updated the datediff function - the way it was written, it would return a negative number (assuming modifieddate was in the past) causing all items to fall under the first case. Thanks to Andriy M for pointing that out
它不是世界上最漂亮的代码,但它确实有效。尝试从三个子查询中进行选择,每个子查询对应一个范围。
It isn't the prettiest code in the world, but it does the trick. Try selecting from three subqueries, one for each range.