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 查询。请注意:empidandleavedt是我表的主键。

4

1 回答 1

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

演示 SQLFiddle

于 2013-05-19T06:21:19.997 回答