国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

SQLserver 實現分組統計查詢(按月、小時分組)

2024-08-31 00:59:35
字體:
來源:轉載
供稿:網友

設置AccessCount字段可以根據需求在特定的時間范圍內如果是相同IP訪問就在AccessCount上累加。

復制代碼 代碼如下:


Create table Counter
(
CounterID int identity(1,1) not null,
IP varchar(20),
AccessDateTime datetime,
AccessCount int
)


該表在這兒只是演示使用,所以只提供了最基本的字段
現在往表中插入幾條記錄
insert into Counter
select '127.0.0.1',getdate(),1 union all
select '127.0.0.2',getdate(),1 union all
select '127.0.0.3',getdate(),1

1 根據年來查詢,以月為時間單位
通常情況下一個簡單的分組就能搞定

復制代碼 代碼如下:


select
convert(varchar(7),AccessDateTime,120) as Date,
sum(AccessCount) as [Count]
from
Counter
group by
convert(varchar(7),AccessDateTime,120)


像這樣分組后沒有記錄的月份不會顯示,如下:

SQLserver 實現分組統計查詢(按月、小時分組)


這當然不是我們想要的,所以得換一種思路來實現,如下:

復制代碼 代碼如下:


declare @Year int
set @Year=2009
select
m as [Date],
sum(
case when datepart(month,AccessDateTime)=m
then AccessCount else 0 end
) as [Count]
from
Counter c,
(
select 1 m
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6
union all select 7
union all select 8
union all select 9
union all select 10
union all select 11
union all select 12
) aa
where
@Year=year(AccessDateTime)
group by
m


查詢結果如下:

SQLserver 實現分組統計查詢(按月、小時分組)


2 根據天來查詢,以小時為單位。這個和上面的類似,代碼如下:

復制代碼 代碼如下:


declare @DateTime datetime
set @DateTime=getdate()
select
right(100+a,2)+ ':00 -> '+right(100+b,2)+ ':00 ' as DateSpan,
sum(
case when datepart(hour,AccessDateTime)> =a
and datepart(hour,AccessDateTime) <b
then AccessCount else 0 end
) as [Count]
from Counter c ,
(select 0 a,1 b
union all select 1,2
union all select 2,3
union all select 3,4
union all select 4,5
union all select 5,6
union all select 6,7
union all select 7,8
union all select 8,9
union all select 9,10
union all select 10,11
union all select 11,12
union all select 12,13
union all select 13,14
union all select 14,15
union all select 15,16
union all select 16,17
union all select 17,18
union all select 18,19
union all select 19,20
union all select 20,21
union all select 21,22
union all select 22,23
union all select 23,24
) aa
where datediff(day,@DateTime,AccessDateTime)=0
group by right(100+a,2)+ ':00 -> '+right(100+b,2)+ ':00 '


查詢結果如下圖:

SQLserver 實現分組統計查詢(按月、小時分組)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贡嘎县| 旬阳县| 多伦县| 陇川县| 西青区| 乐安县| 泰安市| 香格里拉县| 崇阳县| 伽师县| 崇文区| 黔东| 曲阳县| 方山县| 玛纳斯县| 隆子县| 阿拉善盟| 西峡县| 广灵县| 年辖:市辖区| 贵德县| 南岸区| 大渡口区| 涡阳县| 青州市| 遂宁市| 辉县市| 老河口市| 岳普湖县| 溧水县| 武乡县| 中江县| 兰溪市| 北安市| 高要市| 缙云县| 蓬溪县| 中方县| 子长县| 托里县| 彭山县|