SQL 如何按日期范围分组
有人可以帮我弄清楚按日期范围进行分组吗?
现在我有类似这样的查询
Select date, count(x)
from data
group by date
这返回的结果看起来像这样
2011/1/1 10
2011/1/2 5
2011/1/3 8
2011/1/4 3
等等...
但我想每2天计数一次,以便数据看起来像这样
2011/1/1 15
2011/1/3 11
有什么想法吗?
谢谢
Can someone help me figure out to group by a range of dates??
Right now I have query similar to this
Select date, count(x)
from data
group by date
This returns results that look like this
2011/1/1 10
2011/1/2 5
2011/1/3 8
2011/1/4 3
etc...
But I would like to count every 2 days so that the data would look like this
2011/1/1 15
2011/1/3 11
Any ideas??
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过将日期转换为整数值并减少为偶数,将日期标准化为 2 组。一个简单的方法是
val / 2 * 2
,因为第一个/ 2
将被截断任何小数位(只要val 的类型
是一个整数!),* 2
会将其返回到原始值,但标准化为偶数除外。以下是使用 CTE 数据源对结果进行标准化和分组的示例:输出:
You could normalize the dates into groups of 2 by converting to a numerical integer value, and reducing to the even numbers. A simple way to do that is
val / 2 * 2
, because the first/ 2
will be truncated of any decimal places (as long as the type ofval
is an integer!), and* 2
will return it to the original value except normalized to an even number. Here is an example that normalizes and groups the results using a CTE data source:Output: