sql查询如何按每个小时查询那个时间段的总数

username | time |
+-----------+---------------------+
|12345 | 2014-06-23 07:06:37 |
| 12345 | 2014-06-23 8:22:18 |
| 12345| 2014-06-23 9:24:11 |
| 12345 | 2014-06-23 11:28:37 |
|12345 | 2014-06-23 15:03:12 |
| 12345 | 2014-06-23 16:05:27 |
| 12345 | 2014-06-23 22:20:07 |
像上面的那张表,如何按时间段比如7点到8点,8点到9点,9点到10点,一天是24个时间段,一次性查询出来

1、新建JUnit test。

2、使用setUp()和tearDown()方法。

3、分别在两个方法中生成session,开启事务,提交事务和关闭session首先测试本地sql查询,即常用的sql语句通过session的createSQLQuery方法执行sql,并加载要查询的对象 。

4、带条件查询的方法,hibernate利用 :stuName的方式来占用SQL当中的参数,并通过query.setString("参数名","参数") 来进行赋值。

5、对应的查询结果。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-02-25

用group by语句可以实现。

如test表中有如下数据:

要查出2月25号一天中每个小时的cnt的总和,可采用如下语句:

with t as
(select number rn from master..spt_values where type='P' and number<=23)
select t.rn 小时,SUM(isnull(cnt,0)) 数量 from t left join test on t.rn=cast(substring(CONVERT(varchar,begin_date,120),12,2)
as int) group by t.rn

查询结果:

第2个回答  2015-11-12
利用job定时任务执行语句,定义执行间隔为1 小时,
查询条件为 年月日都等于当时的系统时间
字段的小时等于当前的小时 hour(字段)=hour(getdate())
第3个回答  推荐于2017-09-22
select datepart(hh,time), count(username)
from table
group by datepart(hh,time)追问

提示这个FUNCTION a.datepart does not exist

追答

你是用什么数据库啊?

追问

mysql

追答

select datepart(hh,time), count(username)
from table
group by hour(time)

本回答被提问者采纳