0
我有一個應用程序,有1000個用戶在不同時間登錄到各種目的。 現在的任務是想出「高峯時用戶數」 我們在sql中記錄的是userLoginTime,timespent。 這裏的問題是sql服務器表高峯時間
如何實際計算應用程序的高峯時間。 以及如何計算高峯時間的用戶數量。
是否有可能在SQL
我有一個應用程序,有1000個用戶在不同時間登錄到各種目的。 現在的任務是想出「高峯時用戶數」 我們在sql中記錄的是userLoginTime,timespent。 這裏的問題是sql服務器表高峯時間
如何實際計算應用程序的高峯時間。 以及如何計算高峯時間的用戶數量。
是否有可能在SQL
我有一個發揮作用的 - 我與一個記錄會話開始工作,並最終datetime2
值,但希望你能適應當前的數據符合本:
的樣本數據(如果我得到了答案錯了,也許你可以通過這一點,把它添加到你的問題,並添加更多的樣本和預期產出):
create table #Sessions (
--We'll treat this as a semi-open interval - the session was "live" at SessionStart, and "dead" at SessionEnd
SessionStart datetime2 not null,
SessionEnd datetime2 null
)
insert into #Sessions (SessionStart,SessionEnd) values
('20120101','20120105'),
('20120103','20120109'),
('20120107','20120108')
和查詢:
--Logically, the highest number of simultaneous users was reached at some point when a session started
;with StartTimes as (
select distinct SessionStart as Instant from #Sessions
), Overlaps as (
select
st.Instant,COUNT(*) as Cnt,MIN(s.SessionEnd) as SessionEnd
from
StartTimes st
inner join
#Sessions s
on
st.Instant >= s.SessionStart and
st.Instant < s.SessionEnd
group by
st.Instant
), RankedOverlaps as (
select Instant as SessionStart,Cnt,SessionEnd,RANK() OVER (ORDER BY Cnt desc) as rnk
from Overlaps
)
select * from RankedOverlaps where rnk = 1
drop table #Sessions
其中,與我樣本數據得出:
SessionStart Cnt SessionEnd rnk
---------------------- ----------- ---------------------- --------------------
2012-01-03 00:00:00.00 2 2012-01-05 00:00:00.00 1
2012-01-07 00:00:00.00 2 2012-01-08 00:00:00.00 1
的另一種方法,仍使用上述,但如果你也想分析「不太峯」值也,如下:
--An alternate approach - arrange all of the distinct time values from Sessions into order
;with Instants as (
select SessionStart as Instant from #Sessions
union --We want distinct here
select SessionEnd from #Sessions
), OrderedInstants as (
select Instant,ROW_NUMBER() OVER (ORDER BY Instant) as rn
from Instants
), Intervals as (
select oi1.Instant as StartTime,oi2.Instant as EndTime
from
OrderedInstants oi1
inner join
OrderedInstants oi2
on
oi1.rn = oi2.rn - 1
), IntervalOverlaps as (
select
StartTime,
EndTime,
COUNT(*) as Cnt
from
Intervals i
inner join
#Sessions s
on
i.StartTime < s.SessionEnd and
s.SessionStart < i.EndTime
group by
StartTime,
EndTime
)
select * from IntervalOverlaps order by Cnt desc,StartTime
這一次,我輸出時間PE的所有 riods,隨着在時刻(順序從最高到最低)同時使用的用戶號碼一起:
StartTime EndTime Cnt
---------------------- ---------------------- -----------
2012-01-03 00:00:00.00 2012-01-05 00:00:00.00 2
2012-01-07 00:00:00.00 2012-01-08 00:00:00.00 2
2012-01-01 00:00:00.00 2012-01-03 00:00:00.00 1
2012-01-05 00:00:00.00 2012-01-07 00:00:00.00 1
2012-01-08 00:00:00.00 2012-01-09 00:00:00.00 1
這裏是一個溶液解釋:http://connectsql.blogspot.com/2011/01/sql-server- how-to-figure-out-peakoff.html – NinethSense
「userLoginTime」和「timespent」的數據類型是什麼?你試圖找到整個集合中登錄用戶最多的時間間隔? (我說間隔(如果有的話))(並且時間間隔很可能會小於任何覆蓋時間的個人用戶) –
數據類型分別是DateTime和Integer。記錄的時間是從sql的當前日期時間,所以可以是15 :24 12:34種 –