情景:假如有一個登陸日誌表,表名爲sys_loginlog,該表記錄的是用戶使用系統的情況,有一個字段叫logtime,即登陸時間。問題如下:
1.統計某一年各個月用戶登錄系統的情況。
2.統計某一個月用戶登錄系統的情況。
3.統計某一天各個時間段用戶登錄系統的情況。
答案如下,分別使用了oracle 和 sqlserver語法。
- /**統計一年中每月的登錄次數oracl */
- select count(*) as sum ,substr(to_char(t.logintime,'YYYY-MM'),6,2) as month
- from Mwpm_Sys_Loginlog t where
- to_char(t.logintime,'YYYY') = '2009' and t.logintype='0' group by substr(to_char(t.logintime,'YYYY-MM'),6,2)
- /**統計一年中每月的登錄次數sqlserver */
- select count(*) as sum ,substring(convert(char(7),t.logintime,120),6,2) as month
- from Mwpm_Sys_Loginlog t where
- convert(char(4),t.logintime,120) = '2009' and t.logintype='0' group by substring(convert(char(7),t.logintime,120),6,2)
- ///*** 統計一年中各個時間段的登錄次數----------oracle語法**/
- select to_char(t.logintime,'hh24')||':00-'||to_char(to_number(to_char(t.logintime,'hh24'))+1) ||':00' as internal,count(*) as sum,
- to_char(to_number(to_char(t.logintime,'hh24'))) as time from Mwpm_Sys_Loginlog t
- where to_char(t.logintime,'yyyy-MM-dd')='2010-01-18'
- 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')))
- ///*** 統計一年中各個時間段的登錄次數----------sqlserver語法**/
- select convert(char(2),t.logintime,108)+':00-'+ convert(char(2),dateadd(hh,+1,logintime),108)+':00' as internal,count(*) as sum,
- convert(char(2),dateadd(hh,+0,logintime),108) as time
- from
- Mwpm_Sys_Loginlog t where convert(char(10),t.logintime,120)='2010-01-18'
- 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)
- /***統計一年中某個月的每天登陸的次數--oracle***/
- select substr(to_char(t.logintime,'YYYY-MM-DD'),9,9) as day ,count(*) as sum from Mwpm_Sys_Loginlog t
- where to_char(t.logintime,'YYYY-MM') = '2010-01'
- and t.logintype='0' group by to_char(t.logintime,'YYYY-MM-DD')
- /***統計一年中某個月的每天登陸的次數--sqlserver***/
- select substring((convert(char(10),t.logintime,120)),9,2) as day , count(*) as sum
- 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)
- /**find()方法不支持 substring((convert(char(10),t.logintime,120)),9,2)**/