1

我有 2 个表,A 和 B。如果该名称当前不属于 time_start 和 time_end 之间的时间段,我想将名称和“notInTime”插入表 B。

例如:现在时间 = 10:30

TABLE A
NAME TIME_START (DATETIME) TIME_END (DATETIME)
A 12:00 14:00
A 10:00 13:00
B 09:00 11:00
B 10:00 11:00
C 12:00 14:00
D 16:00 17:00

Table B
Name Indicator
A intime
B intime

如果运行查询应将以下内容添加到表 B

C notInTime
D notinTime
4

4 回答 4

2
INSERT INTO TABLE_B b (column_name_1, column_name_2)
SELECT 
'C', 
CASE WHEN EXISTS (SELECT 1 FROM TABLE_A a WHERE a.NAME = 'C' AND '10:30' BETWEEN TIME(a.TIME_START) AND TIME(a.TIME_END)) THEN 'intime' ELSE 'notinTime' END
UNION ALL 
SELECT 
'D', 
CASE WHEN EXISTS (SELECT 1 FROM TABLE_A a WHERE a.NAME = 'D' AND '10:30' BETWEEN TIME(a.TIME_START) AND TIME(a.TIME_END)) THEN 'intime' ELSE 'notinTime' END
于 2013-08-08T11:55:25.860 回答
1

这会将及时和未及时添加到 table_b

declare @now time = '10:30'

INSERT INTO TABLE_B(Name, Indicator)
select 
a.NAME, case when b.chk = 1 THEN 'intime' else 'notInTime' end
from 
(
select distinct NAME from TABLE_A
) a
outer apply
(select top 1 1 chk from TABLE_A 
where @now between TIME_START and TIME_END and a.Name = Name) b
于 2013-08-08T12:00:03.013 回答
0

试过了BETWEEN吗?

  INSERT INTO TABLE B 
 (SELECT DISTINCT
         name
       , 'notInTime'
    FROM A
  WHERE '10:30' NOT BETWEEN TIME(a.TIME_START) AND TIME(a.TIME_END))
于 2013-08-08T11:58:42.477 回答
0

就像@trapicki 所说的那样,但没有理由对时间进行硬编码。

insert
  into b
  (select distinct name,
                   'notInTime'
     from a
     where sysdate not between a.time_start and a.time_end)
于 2013-08-08T12:44:30.427 回答