日期:2014-05-16  浏览次数:21180 次

求救SQL分组查询统计查询语句
有一用户表格user,有三个字段,
序号 姓名 登录日期
1 a 2009-3-1
2 ab 2009-4-15
3 abc 2009-5-15
4 a 2009-3-15 
现在我想用SQL查询出全部用户指定日期范围内每月的登录次数,如果该月没有登录,则统计为0.这个语句该怎么写呢?谢谢回答!
要求结果为
姓名 次数 日期
a 2 2009-3
ab 0 2009-3
abc 0 2009-3
a 0 2009-4
ab 1 2009-4
bc 0 2009-4
a 0 2009-5
ab 0 2009-5
abc 1 2009-5


------解决方案--------------------
SQL code
create table tb(序号 int, 姓名 varchar(10), 登录日期 datetime)
insert into tb values(1 , 'a' , '2009-3-1') 
insert into tb values(2 , 'ab', '2009-4-15') 
insert into tb values(3 , 'abc', '2009-5-15') 
insert into tb values(4 , 'a' , '2009-3-15')
go

select t1.姓名 , isnull(t2.次数,0) 次数 , t1.登录日期 日期 from
(select distinct m.姓名 , convert(varchar(7),n.登录日期,120) 登录日期 from tb m , tb n) t1
left join
(select 姓名 , convert(varchar(7),登录日期,120) 登录日期 , count(1) 次数 from tb group by 姓名 , convert(varchar(7),登录日期,120)) t2
on t1.姓名 = t2.姓名 and t1.登录日期 = t2.登录日期
order by t1.登录日期 , t1.姓名

drop table tb 

/*
姓名         次数          日期
---------- ----------- -------
a          2           2009-03
ab         0           2009-03
abc        0           2009-03
a          0           2009-04
ab         1           2009-04
abc        0           2009-04
a          0           2009-05
ab         0           2009-05
abc        1           2009-05

(9 行受影响)

*/

------解决方案--------------------
SQL code
select u1.姓名,u1.日期,count(u2.序号) as 次数 
from (select distinct a.姓名,format(b.登录日期,'yyyy-mm') as 日期 from [User] a,[User] b) u1 
    left join [User] u2 on u1.姓名=u2.姓名 and u1.日期=format(u2.登录日期,'yyyy-mm')  
where format(u2.登录日期,'yyyy-mm-dd') between '2009-01-01' and '2010-07-31'  
or u2.登录日期 is null
group by u1.姓名,u1.日期 
order by u1.日期