加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SqlServer 数据库按日期分组查询。

发布时间:2020-12-12 12:47:21 所属栏目:MsSql教程 来源:网络整理
导读:要求? ? 两个时间点:一个开始时间(2007/09/08 09:10:43),一个结束时间(2007/10/09 04:32:37) ? ?? ?? ?? ???数据库中表的字段有 id(编号)??name(名字)? ?time(注册时间) 表名为table ? ?? ?? ?? ?? ?? ?? ?? ?需要查询比如在两个时间段内 比如如上面时间点?
要求? ? 两个时间点:一个开始时间(2007/09/08 09:10:43),一个结束时间(2007/10/09 04:32:37)
? ?? ?? ?? ???数据库中表的字段有 id(编号)??name(名字)? ?time(注册时间) 表名为table
? ?? ?? ?? ?? ?? ?? ?? ?需要查询比如在两个时间段内 比如如上面时间点?
? ?? ?? ?? ?? ?? ???求:1.9月,10月分别有多少个id?
? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ???2.两个时间段的单个日中分别有多少个id?
? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ???3两个时间段的单个小时中分别有多少个id?
??我的思路是分别按 月,日,小时分组,然后统计???select count(id) from table where time>='2007/09/08 09:10:43' and time<=
'2007/10/09 04:32:37'?
? ???但我做出来的都只能按秒分组,请各位高人指点 怎么才能实现 按月或者按日,按小时分组?先谢谢啦!!


--按照月份统计
select count(id) cnt,datepart(mm,time) [Month]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(mm,time)
--按照日统计
select count(id) cnt,datepart(dd,time) [Day]
from [table]
where time between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(dd,time)
--按照小时统计
select count(id) cnt,datepart(hh,time) [Hour]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(hh,time)

转自 http://www.itpub.net/thread-917632-1-1.html



版主

卡卡西

精华贴数 0 专家积分 0 技术积分 4377 社区积分 0 注册时间 2007-3-10 论坛徽章: 22

'会员2007贡献徽章

'2012新春纪念徽章

'2012新春纪念徽章

'2012新春纪念徽章

'2012新春纪念徽章

'马上有车

'马上有房

'马上有钱

'马上有对象

'2012新春纪念徽章

'管理团队成员

'2011新春纪念徽章

  • 加好友
  • 发消息
2#

? 发表于 2007-12-27 16:23:45? | 只看该作者 --按照月份统计 select count(id) cnt,time) [Month] from [table] where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37' group by datepart(mm,time) --按照日统计 select count(id) cnt,time) [Day] from [table] where time between '2007/09/08 09:10:43' and '2007/10/09 04:32:37' group by datepart(dd,time) --按照小时统计 select count(id) cnt,time) [Hour] from [table] where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37' group by datepart(hh,time)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!


    推荐文章
      热点阅读