項目中比較實用的統計查詢

情景:假如有一個登陸日誌表,表名爲sys_loginlog,該表記錄的是用戶使用系統的情況,有一個字段叫logtime,即登陸時間。問題如下:

1.統計某一年各個月用戶登錄系統的情況。

2.統計某一個月用戶登錄系統的情況。

3.統計某一天各個時間段用戶登錄系統的情況。

答案如下,分別使用了oracle 和 sqlserver語法。

Code:
  1. /**統計一年中每月的登錄次數oracl */   
  2.  select  count(*) as sum ,substr(to_char(t.logintime,'YYYY-MM'),6,2) as month  
  3.   from  Mwpm_Sys_Loginlog  t   where    
  4.   to_char(t.logintime,'YYYY')  = '2009'   and t.logintype='0'  group   by  substr(to_char(t.logintime,'YYYY-MM'),6,2)   
  5.   
  6. /**統計一年中每月的登錄次數sqlserver */   
  7.  select  count(*) as sum ,substring(convert(char(7),t.logintime,120),6,2) as month  
  8.   from  Mwpm_Sys_Loginlog  t   where    
  9.   convert(char(4),t.logintime,120)  = '2009'   and t.logintype='0'  group   by  substring(convert(char(7),t.logintime,120),6,2)   
  10.   
  11. ///*** 統計一年中各個時間段的登錄次數----------oracle語法**/   
  12. select to_char(t.logintime,'hh24')||':00-'||to_char(to_number(to_char(t.logintime,'hh24'))+1) ||':00' as internal,count(*) as  sum,   
  13. to_char(to_number(to_char(t.logintime,'hh24'))) as time    from  Mwpm_Sys_Loginlog t    
  14. where   to_char(t.logintime,'yyyy-MM-dd')='2010-01-18'    
  15.  group by to_char(t.logintime,'hh24')||':00-'||to_char(to_number(to_char(t.logintime,'hh24'))+1)||':00',to_char(to_number(to_char(t.logintime,'hh24')))    
  16.   
  17.   
  18. ///*** 統計一年中各個時間段的登錄次數----------sqlserver語法**/   
  19. select convert(char(2),t.logintime,108)+':00-'convert(char(2),dateadd(hh,+1,logintime),108)+':00' as internal,count(*) as sum,   
  20. convert(char(2),dateadd(hh,+0,logintime),108) as time    
  21. from     
  22.   Mwpm_Sys_Loginlog t  where     convert(char(10),t.logintime,120)='2010-01-18'    
  23.   group by convert(char(2),t.logintime,108)+':00-'convert(char(2),dateadd(hh,+1,logintime),108)+':00',convert(char(2),dateadd(hh,+0,logintime),108)   
  24.   
  25.   
  26. /***統計一年中某個月的每天登陸的次數--oracle***/   
  27. select  substr(to_char(t.logintime,'YYYY-MM-DD'),9,9) as day ,count(*) as sum  from  Mwpm_Sys_Loginlog  t     
  28.                  where   to_char(t.logintime,'YYYY-MM')   = '2010-01'  
  29.                    and t.logintype='0'  group   by   to_char(t.logintime,'YYYY-MM-DD')   
  30.   
  31.   
  32. /***統計一年中某個月的每天登陸的次數--sqlserver***/   
  33. select  substring((convert(char(10),t.logintime,120)),9,2) as day , count(*) as sum  
  34.  from  Mwpm_Sys_Loginlog  t where  convert(char(7),t.logintime,120) = '2010-01' group by substring(convert(char(10),t.logintime,120),9,2)   
  35.   
  36. /**find()方法不支持  substring((convert(char(10),t.logintime,120)),9,2)**/  

 

 

發佈了42 篇原創文章 · 獲贊 4 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章