2016-11-23 5 views
1

create_timestampとlast_loginの日付に基づいて、年単位でユーザーを実行したいとします。create_timestampと最終ログイン日数でユーザーをカウントする

USER create_timestamp Last_login 
10 2009-06-18  20161029 
11 2010-07-01  20110101 
12 2011-10-01  20150101 
13 2012-12-01  20161101 

Year Count 
2009 1 
2010 2 
2011 3 
2012 3 
2013 3 
2014 3 
2015 3 
2016 2 

私はsumとcase文を使用して調べるでしょうか?

+0

すでに微調整できたクエリはありますか? – mendosi

答えて

0

あなたはcreate_timestampとLast_loginにインデックスを持っている場合は、以下のような外部参照テーブルを作成してみ永久テーブルとして作成し(私はここで一時テーブルを使用していた)、その後のような

create table #xref(yearofemp int) 
insert into #xref values(2009) 
insert into #xref values(2010) 
insert into #xref values(2011) 
insert into #xref values(2012) 
insert into #xref values(2013) 
insert into #xref values(2014) 
insert into #xref values(2015) 
insert into #xref values(2016) 

create table #emp(userid int,create_timestamp datetime,Last_login datetime) 
insert into #emp values(10,'2009-06-18','20161029') 
insert into #emp values(11,'2010-07-01','20110101') 
insert into #emp values(12,'2011-10-01','20150101') 
insert into #emp values(13,'2012-12-01','20161101') 


select 
    a.yearofemp as Year_No 
    ,COUNT(a.userid) as Count_of_emp 
from 
(
select 
    #emp.userid 
    ,#xref.yearofemp 
from #emp 
inner join #xref 
on yearofemp between year(#emp.create_timestamp) 
and year(#emp.Last_login) 
)a 
group by a.yearofemp 
order by a.yearofemp 
0

の下にあなたのテーブルに参加し、 、このクエリはそれを使用することができます。


create table #years(years datetime not null) 
insert into #years 
    values 
     ('2009-01-01'), 
     ('2010-01-01'), 
     ('2011-01-01'), 
     ('2012-01-01'), 
     ('2013-01-01'), 
     ('2014-01-01'), 
     ('2015-01-01'), 
     ('2016-01-01') 

create table #data(
    userid int, 
    create_timestamp datetime, 
    Last_login datetime 
) 

insert into #data 
    values 
     (10,'2009-06-18','20161029'), 
     (11,'2010-07-01','20110101'), 
     (12,'2011-10-01','20150101'), 
     (13,'2012-12-01','20161101'), 



select 
    year(y.years) as [Year], 
    ca.[Count] 
from #years y 
outer apply (
    select 
     count(*) as [Count] 
    from #data d 
    where y.years between d.create_timestamp and d.Last_login 
) ca 
 
関連する問題