SQLserver中怎么实现分组统计查询-成都快上网建站

SQLserver中怎么实现分组统计查询

SQLserver 中怎么实现分组统计查询,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

从网站建设到定制行业解决方案,为提供做网站、成都做网站服务体系,各种行业企业客户提供网站建设解决方案,助力业务快速发展。创新互联将不断加快创新步伐,提供优质的建站服务。

设置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)

像这样分组后没有记录的月份不会显示,如下: 这当然不是我们想要的,所以得换一种思路来实现,如下:复制代码 代码如下: 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

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) '+right(100+b,2)+ ':00 

关于SQLserver 中怎么实现分组统计查询问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


新闻标题:SQLserver中怎么实现分组统计查询
分享路径:http://kswjz.com/article/ijgdgh.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流