2017-06-29 30 views
2

請你看看下面的任務嗎?SQL Server特有的缺勤期

我有一個表DATA結構如下:

CREATE TABLE DATA 
(
    EMPLOYEE nvarchar(50) NOT NULL, 
    ABSENCE_START nvarchar(50) NOT NULL, 
    ABSENCE_END nvarchar(50) NOT NULL 
) 

它包含以下數據:

insert into DATA (EMPLOYEE, ABSENCE_START, ABSENCE_END) 
values ('emp01','21/06/2017','22/06/2017'), 
     ('emp01','24/06/2017','27/06/2017'), 
     ('emp02','22/06/2017','24/06/2017'), 
     ('emp02','22/06/2017','27/06/2017') 

正如你可以看到「emp02」員工,我們有沒有兩個時間段和其中一個(第4行)完全包含另一段缺席(第3行)。

我需要將這兩行合併爲一行(第4行)。

預期的結果將是:

EMPLOYEE ABSENCE_START ABSENSE 
--------------------------------------- 
emp01  21/06/2017  22/06/2017 
emp02  24/06/2017  27/06/2017 
emp01  22/06/2017  27/06/2017 

預先感謝您!

+0

你有沒有試圖解決你的問題? –

+0

我嘗試使用MAX和MIN聚合函數。但是這也爲'emp01'員工合併了數據。 –

+1

您應**總是**將日期存儲爲數據類型'DATE'或'DATETIME2(n)' - ** NOT **作爲'nvarchar'! –

回答

0

如果你正在尋找的唯一重疊校正是當一行完全包含另一個,你有沒有唯一的行標識符,您可以使用not exists()像這樣:

set dateformat dmy; 
;with cte as (
    select 
     employee 
    , absence_start= convert(date,absence_start) 
    , absence_end = convert(date,absence_end) 
    from data 
)  
select * 
from cte d 
where not exists (
    select 1 
    from cte i 
    where i.employee=d.employee 
     and i.absence_start <= d.absence_start 
     and i.absence_end >= d.absence_end 
     and (i.absence_start <> d.absence_start 
     or i.absence_end <> d.absence_end) 
    ) 

rextester演示:http://rextester.com/PHF88226

回報:

+----------+---------------+-------------+ 
| employee | absence_start | absence_end | 
+----------+---------------+-------------+ 
| emp01 | 2017-06-21 | 2017-06-22 | 
| emp01 | 2017-06-24 | 2017-06-27 | 
| emp02 | 2017-06-22 | 2017-06-27 | 
+----------+---------------+-------------+ 
+0

您是否注意到日期是鍵入nvarchar? –

+0

它產生以下結果: emp01 \t \t 21/06/2017 22/06/2017 emp01 \t \t 24/06/2017 27/06/2017 emp02 \t \t 22/06/2017 24/06/2017 –

+0

Hannoun Yassir,是的,在這裏我們應該使用CONVERT(DATE,ABSENSE_START,103)等... –

0

查詢應該是這樣的:

select 
* 
from dbo.DATA t1 
where not exists (
      select 
      * 
      from dbo.DATA t2 
      where t1.ABSENCE_START >= t2.ABSENCE_START 
       and t1.ABSENCE_END < t2.ABSENCE_END) 

但是如果你有重疊的缺席。像這樣:

insert into DATA(EMPLOYEE,ABSENCE_START,ABSENCE_END) values 
('emp01','21/06/2017','22/06/2017'), 
('emp01','24/06/2017','27/06/2017'), 
('emp02','22/06/2017','29/06/2017'), 
('emp02','22/06/2017','27/06/2017') 
+0

謝謝Dean!如果你的意思是部分重疊,例如 emp02 '22/06/2017''25/06/2017' emp02 '21/06/2017''24/06/2017' –

+0

@DavidFreeman,是的,這就是我的意思。在這種情況下你期望得到什麼結果? –