2016-10-11 6 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 =シェフ

今私は2が

ないときに1が作動している時間を表示したいですこの例では

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 

ただ一つの作業の男と1つのchがあります:このように

しかし、これはサーバー作業部長とサーバー責任者にまで拡張する必要があります

この問題を解決するにはどうすればよいのですか。

+0

最後の行( 'people_id = 2')は、第1行の時間の間にあるので、シェフが通常の仕事をしているときに働いているとは限りませんか? –

+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