Sql代碼 收藏代碼 --創建考勤記錄表 CREATE TABLE T_ATTENDANCE_LOG ( ID_ VARCHAR(36), USERNAME_ VARCHAR(255), LOGDATE_ VARCHAR(100) ) --初始化一些測試數據 insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('1','張三','2014-02-01'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('2','張三','2014-02-02'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('3','張三','2014-02-03'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('4','張三','2014-02-04'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('5','張三','2014-02-05'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('6','張三','2014-02-06'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('11','李四','2014-03-01'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('12','李四','2014-04-01'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('13','李四','2014-05-01'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('21','王五','2014-02-15'); insert into T_ATTENDANCE_LOG (ID_,USERNAME_,LOGDATE_) VALUES ('22','王五','2014-03-15'); --查詢 SELECT T.*,T.ROWID FROM T_ATTENDANCE_LOG T;
結果:
1.統計員工2014年的每月出勤情況
Sql代碼 收藏代碼 with sql1 as ( select USERNAME_,substr(LOGDATE_,0,7) as a,count(LOGDATE_) as b from T_ATTENDANCE_LOG group by USERNAME_,substr(LOGDATE_,0,7) ) select USERNAME_, sum(case A when '2014-01' then B end) 一月, sum(case A when '2014-02' then B end) 二月, sum(case A when '2014-03' then B end) 三月, sum(case A when '2014-04' then B end) 四月, sum(case A when '2014-05' then B end) 五月, sum(case A when '2014-06' then B end) 六月, sum(case A when '2014-07' then B end) 七月, sum(case A when '2014-08' then B end) 八月, sum(case A when '2014-09' then B end) 九月, sum(case A when '2014-10' then B end) 十月, sum(case A when '2014-11' then B end) 十一月, sum(case A when '2014-12' then B end) 十二月 from sql1 group by USERNAME_ 這裡用到“sql統計利器”--with。
結果:
2.查詢每個人的出勤記錄
Sql代碼 收藏代碼 select USERNAME_ as 員工,wmsys.wm_concat(LOGDATE_) as 出勤記錄 from T_ATTENDANCE_LOG t group by USERNAME_
結果:
但是我們發現這個統計出來的結果是亂序,改造一下
Sql代碼 收藏代碼 select USERNAME_ as 員工, max(r) as 出勤記錄 from ( select USERNAME_,wmsys.wm_concat(LOGDATE_) OVER(PARTITION BY USERNAME_ ORDER BY LOGDATE_) r from T_ATTENDANCE_LOG t )group by USERNAME_
改造結果:
3.獲得每個員工第一天上班的出勤記錄
Sql代碼 收藏代碼 SELECT * FROM ( --分組排序加序號 select USERNAME_,LOGDATE_,ROW_NUMBER() OVER(PARTITION BY USERNAME_ ORDER BY LOGDATE_) r from T_ATTENDANCE_LOG t group by USERNAME_,LOGDATE_ ) where R=1
結果: