读书人

查询新增人员数量,该怎么解决

发布时间: 2014-01-22 14:50:12 作者: rapoo

查询新增人员数量
做统计的,查询每天的新增的人员
表结构
userid datetime
1 2014-01-13
2 2014-01-13
3 2014-01-13
1 2014-01-14
4 2014-01-14

结果
2014-01-13 为三个人
2014-01-14 为一个

2014-01-14 编号为1的在13号登录过所以不是新增的。4在14之前没有登录过所以是新增的
一句话,每天的登录记录中,之前没有登录过的算是新增的
[解决办法]

create table test(userid int, datetime datetime)

insert into test
select 1 ,'2014-01-13' union all
select 2 ,'2014-01-13' union all
select 3 ,'2014-01-13' union all
select 1 ,'2014-01-14' union all
select 4 ,'2014-01-14'
go


IF object_id('tempdb..#t','U')IS NOT NULL
DROP TABLE #t
select *,
(select COUNT(*) from test t2
where t1.userid = t2.userid and t1.datetime>=t2.datetime) rownum INTO #t
from test t1

select datetime,COUNT(*) '人数',(SELECT COUNT(1) FROM #t b WHERE a.datetime=b.datetime)[总人数]
from #t a
where rownum = 1
group by datetime
/*
datetime 人数 总人数
----------------------- ----------- -----------
2014-01-13 00:00:00.000 3 3
2014-01-14 00:00:00.000 1 2

*/

[解决办法]
引用:
还要添加一列,就是计算当日的总人数呢

datetime 人数 总人数
2014-01-13 00:00:00.000 3 3
2014-01-14 00:00:00.000 1 2


修改了一下:
--drop table test

create table test(userid int, datetime datetime)

insert into test
select 1 ,'2014-01-13' union all
select 2 ,'2014-01-13' union all
select 3 ,'2014-01-13' union all
select 1 ,'2014-01-14' union all
select 4 ,'2014-01-14'
go

select datetime,COUNT(*) '人数',
(select COUNT(*) from test t2 where t2.datetime = t.datetime) as 总人数
from
(
select *,
(select COUNT(*) from test t2
where t1.userid = t2.userid and t1.datetime>=t2.datetime) rownum
from test t1
)t
where rownum = 1
group by datetime
/*
datetime人数总人数
2014-01-13 00:00:00.00033
2014-01-14 00:00:00.00012
*/

读书人网 >SQL Server

热点推荐