2013-05-19 71 views
0

我有一個LEAVE表中的記錄數如下如何獲取的基礎上不斷變化的列值

EMPID  LEAVEDT  APPDT  LEAVETYPE 
------  -------  ------- --------- 
E1   10-3-13  5-3-13  CL 
E1   11-3-13  5-3-13  CL 
E1   12-3-13  5-3-13  CL 
E1   13-3-13  5-3-13  SL 
E1   14-3-13  5-3-13  SL 
E1   15-3-13  5-3-13  PL 
E1   16-3-13  5-3-13  CL 
E1   17-3-13  5-3-13  CL 
E1   18-3-13  5-3-13  PL 
E1   19-3-13  5-3-13  PL 
E1   20-3-13  5-3-13  CL 

現在我要取的,我想顯示有多少次,多少天的記錄員工E1已經採取了各種類型的休假。對於上面的例子我的查詢結果應該是:---

EMPID  FROM  TO   LEAVETYPE 
-----  ----- ------  --------- 
E1   10-3-13 12-3-13  CL 
E1   13-3-13 14-3-13  SL 
E1   15-3-13 15-3-13  PL 
E1   16-3-13 17-3-13  CL 
E1   18-3-13 19-3-13  PL 
E1   20-3-13 20-3-13  CL 

請幫我用合適的SQL查詢。 請注意:empidleavedt是我桌子的主鍵。

回答

0

對錶格結構做如下修改。

 create table leaves (empid varchar(10) , 
       leavefromdt date, 
       leavetodate date, 
       appdate date, 
       leavetype varchar(2)); 

樣本數據

 insert into leaves values('E1', Cast('3-10-2013' as datetime), 
     Cast('3-12-2013' as datetime), Cast('3-5-2013' as datetime),'CL'); 

     insert into leaves values('E1',Cast('3-13-2013'as datetime), 
     Cast('3-14-2013'as datetime),Cast('5-3-2013'as datetime),'SL'); 

     insert into leaves values('E1',Cast('3-15-2013'as datetime), 
     Cast('3-15-2013'as datetime),Cast('5-3-2013'as datetime),'PL'); 

     insert into leaves values('E1',Cast('3-16-2013'as datetime), 
     Cast('3-17-2013'as datetime),Cast('5-3-2013'as datetime),'CL'); 

查詢

 select * , DATEDIFF(DAY, leavefromdt,leavetodate)+1 days from leaves 
     order by empid,leavetype 

Demo SQLFiddle