【问题标题】:sql date-time comparison of people人的sql日期时间比较
【发布时间】:2016-10-11 14:42:26
【问题描述】:

我想在没有厨师的情况下列出人员名单。

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 

在这个例子中只有一名工人和一名厨师,但这必须扩展到几位工人和几位酋长

如何进行 sql 查询来解决这个问题。

【问题讨论】:

  • 最后一行 (people_id = 2) 时间在第一行时间之间,所以这并不意味着厨师在正常人工作时工作?
  • 能否多添加几行样表数据,调整一下预期的结果?
  • @a_horse_with_no_name sql 2008 r2
  • @Prdp 没错。我想显示有人在没有厨师的情况下工作的时间。
  • 我认为你的输出现在应该有第三行了; 1 2016-10-11 06:57:02.000 2016-10-11 14:58:23.000因为此时没有厨师可用

标签: sql sql-server date time between


【解决方案1】:

好吧,它看起来并不“漂亮”,我明天会尝试找到更好的解决方案。

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) 

【讨论】:

  • 感谢您的意见!但是我怎样才能让我有一群人,我想和一群厨师进行比较。所以我可以显示有人在没有厨师的情况下工作的时间。
猜你喜欢
  • 2014-09-11
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多