表描述 某天 某账号 登录次数
date(datetime) accountid(varchar(20)) logincount(int)
表是截面数据,某该帐号没有登录,则也会有数据,只是logincount=0
求sql 某天的活跃账号数(即最近七天登录次数大于等于3次的账号数)
求某段时间内的活跃帐号数.谢谢
/*create table bw24417
(
[date] datetime,
accountid varchar(20),
logincount int
)
insert into bw24417 values (GETDATE(),'1',1);
insert into bw24417 values (GETDATE(),'3',1);
insert into bw24417 values (GETDATE(),'1',1);
insert into bw24417 values (GETDATE(),'1',1);
insert into bw24417 values (GETDATE(),'2',1);
insert into bw24417 values (GETDATE(),'1',1);
insert into bw24417 values (GETDATE(),'2',1);
insert into bw24417 values (GETDATE(),'4',1);
insert into bw24417 values (GETDATE(),'3',1);
insert into bw24417 values (GETDATE(),'4',1);
insert into bw24417 values (GETDATE(),'3',1);
*/
select * from bw24417;
select accountid,count(logincount) AS huoyue from bw24417 where DATEDIFF(day,[date],GETDATE())<7 group by accountid having count(logincount)>2;
结果:
date accountid logincount
----------------------- -------------------- -----------
2011-04-25 11:30:20.167 1 1
2011-04-25 11:30:20.190 3 1
2011-04-25 11:30:20.190 1 1
2011-04-25 11:30:20.190 1 1
2011-04-25 11:30:20.200 2 1
2011-04-25 11:30:20.200 1 1
2011-04-25 11:30:20.200 2 1
2011-04-25 11:30:20.200 4 1
2011-04-25 11:30:20.200 3 1
2011-04-25 11:30:20.200 4 1
2011-04-25 11:30:20.200 3 1
(11 row(s) affected)
accountid huoyue
-------------------- -----------
1 4
3 3
(2 row(s) affected)
select
convert(varchar(6),date,112),
accountid From [table] Group By convert(varchar(6),date,112) Having lodincount>2
推荐一篇博客
http://www.cnblogs.com/mapeng-11/archive/2011/03/09/1978417.html
declare @days int,@count int,@date datetime
set @days=7
set @count=3
set @date=getdate()
select accountid from [loginInfoTable]
where datediff(dd,@date,[date])<@days
group by accountid
having sum(logincount)>=@count