1 use ResourceShare 2 --統計使用情況 3 alter PROCEDURE StaSheryUse 4 @start datetime, 5 @end datetime, 6 @orgId int 7 AS 8 BEGIN 9 10 11 create table #Month 12 ( 13 id int IDENTITY (1,1) primary key not null, 14 [year] int not null, 15 [month] int not null 16 ) 17 18 19 --計算全文傳遞數 20 21 select * into #FullTextTask from (select COUNT(1) fulltextCount,YEAR(CreateDate) [year],MONTH(CreateDate) [month] from FullTextTask where OrganId=@orgId and ([State]=4 or [State]=5) and (CreateDate BETWEEN @start AND @end) group by YEAR(CreateDate),MONTH(CreateDate)) a 22 23 --計算數據庫訪問次數 24 25 select * into #DBVisitTask from (select COUNT(1) dbvisitCount,YEAR(CreateDate) [year],MONTH(CreateDate) [month] from DBVisitTask where OrganId=@orgId and ([State]=1 or [State]=3) and (CreateDate BETWEEN @start AND @end) group by YEAR(CreateDate),MONTH(CreateDate)) b 26 27 --計算用戶數 28 select * into #IdentityUser from (select COUNT(1) userCount,YEAR(CreateTime) [year],MONTH(CreateTime) [month] from IdentityUser where OrganId=@orgId and (CreateTime BETWEEN @start AND @end) group by YEAR(CreateTime),MONTH(CreateTime)) c 29 30 --計算用戶登錄次數 31 select * into #UserLoginRecord from (select COUNT(1) loginTimes,YEAR(LoginDate) [year],MONTH(LoginDate) [month] from UserLoginRecord r left join IdentityUser u on r.UserId=u.Id where OrganId=@orgId and (LoginDate BETWEEN @start AND @end) group by YEAR(LoginDate),MONTH(LoginDate)) d 32 33 34 35 36 insert into #Month([year],[month]) select [year],[month] from #FullTextTask 37 insert into #Month([year],[month]) select [year],[month] from #DBVisitTask 38 insert into #Month([year],[month]) select [year],[month] from #IdentityUser 39 insert into #Month([year],[month]) select [year],[month] from #UserLoginRecord 40 41 42 select * into #yearAndMonth from(select [year],[month] from #Month group by [year],[month]) a 43 44 45 46 47 select * from (select isnull(userCount, 0) UserCount,isnull(dbvisitCount, 0) DBvisitCount,isnull(fulltextCount, 0) FulltextCount,isnull(loginTimes, 0) LoginTimes,m.[year] [Year],m.[month] [Month] from #yearAndMonth m 48 49 left join #UserLoginRecord a on a.[year]=m.[year] and a.[month]=m.[month] 50 left join #DBVisitTask b on b.[year]=m.[year] and b.[month]=m.[month] 51 left join #FullTextTask c on c.[year]=m.[year] and c.[month]=m.[month] 52 left join #IdentityUser d on d.[year]=m.[year] and d.[month]=m.[month]) f order by [Year] desc,[Month] 53 54 END 55 56 57 execute StaSheryUse '2017-04-16','2017-04-17 23:59:59',7
這段代碼,我簡要地介紹下,存儲過程接收了兩個參數,一個開始日期,一個結束日期。根據傳進來的日期范圍統計全文傳遞數,用戶注冊數等。11行,創建了一個月份的臨時表,包括年和月兩個字段。它的數據來源於其它所有要統計的表。之后42行,定義了一個#yearAndMonth的臨時表,主要是把#Month表中的重復數據過濾掉。最后把眾多的統計臨時表和#yearAndMonth左鏈接查詢,即可得到結果,結果是根據年份和月份統計的二維表。
