2016-10-11 66 views
1

我想列出一個沒有大廚時工作的人。sql日期時間比較人

SQL表:

people_id clock_in    clock_out 
1   2016-10-10 06:58:01.000 2016-10-10 14:59:01.000 
1   2016-10-11 06:57:02.000 2016-10-11 14:58:23.000 
.. 
2   2016-10-10 07:51:01.000 2016-10-10 13:00:01.000 

People_id:1 =正常工作的人,2 =廚師在這個例子中

現在我想顯示的時間是1時,工作時,2是不是有

像這樣:

people_id start_working_without_chef end_working_without_chef 
1   2016-10-10 06:58:01.000 2016-10-10 07:51:01.000 
1   2016-10-10 13:00:01.000 2016-10-10 14:59:01.000 

在這個例子中,只有一個人工作,一個通道EF但是這必須擴展到serveral的工作男子和serveral的酋長

我怎樣才能使一個SQL查詢來解決這個問題。

+0

最後一行('people_id = 2')時間在第一排時間之間,這並不意味着廚師在正常工作時工作嗎? –

+0

您可以添加更多行樣本表數據,並調整預期結果嗎? – jarlh

+0

@a_horse_with_no_name sql 2008 r2 – Scaver

回答

0

以及它不是真正的「好」看,我會盡力,明天找到一個更好的解決方案。

create table tt (id int, dte_in timestamp, dte_out timestamp); 

insert into tt values (1, timestamp('2016-10-10-06.58.01'), timestamp('2016-10-10-14.59.01')); 
insert into tt values (1, timestamp('2016-10-11 06:57:02'), timestamp('2016-10-11 14:58:23')); 
insert into tt values (1, timestamp('2016-10-12 06:57:02'), timestamp('2016-10-12 14:58:23')); 
insert into tt values (1, timestamp('2016-10-13 06:57:02'), timestamp('2016-10-13 14:58:23')); 
insert into tt values (1, timestamp('2016-10-14 06:57:02'), timestamp('2016-10-14 14:58:23')); 
insert into tt values (2, timestamp('2016-10-10 07:51:01'), timestamp('2016-10-10 13:00:01')); 
insert into tt values (2, timestamp('2016-10-12 05:57:02'), timestamp('2016-10-12 15:58:23')); 
insert into tt values (2, timestamp('2016-10-13 05:57:02'), timestamp('2016-10-13 12:58:23')); 
insert into tt values (2, timestamp('2016-10-14 10:57:02'), timestamp('2016-10-14 16:58:23')); 


select a.id, 
a.dte_in, 
b.dte_in 
from tt a 
inner join tt b on b.id = 2 and b.dte_in between a.dte_in and a.dte_out 
where a.id = 1 
union all 
select a.id, 
b.dte_out, 
a.dte_out 
from tt a 
inner join tt b on b.id = 2 and b.dte_out between a.dte_in and a.dte_out 
where a.id = 1 
union all 
select a.id, a.dte_in, a.dte_out 
from tt a 
where a.id = 1 and not exists (select 1 from tt b where b.id = 2 and b.dte_in between a.dte_in and a.dte_out) 
and not exists (select 1 from tt b where b.id = 2 and a.dte_in between b.dte_in and b.dte_out) 
+0

感謝您的輸入!但我怎麼能做到這一點,以便我有一羣我想與一羣廚師進行比較的人。所以我可以展示有人在沒有任何廚師的情況下工作的時間。 – Scaver