SQL语句如何实现按月分组统计查询

时间:2025-05-10

SQL语句如何实现按月分组统计查询

SQL语句如何实现按月分组统计查询?首先创建数据表IP地址,访问时间和访问次数。如果每访问一次就插入一条记录,那么AccessCount可以不要,查询时使用count就可以了,这样当访问量很大的时候会对数据库造成很大压力。设置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)

像这样分组后没有记录的月份不会显示,如下:

SQL语句如何实现按月分组统计查询

这当然不是我们想要的,所以得换一种思路来实现,如下:

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

查询结果如下:

SQL语句如何实现按月分组统计查询

SQL语句如何实现按月分组统计查询.doc 将本文的Word文档下载到电脑

    精彩图片

    热门精选

    大家正在看

    × 游客快捷下载通道(下载后可以自由复制和排版)

    限时特价:7 元/份 原价:20元

    支付方式:

    开通VIP包月会员 特价:29元/月

    注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
    微信:fanwen365 QQ:370150219