我有2个表,A和B.如果该名称当前不属于time_start和time_end之间的时间段,我想在表B中插入名称和'notInTime'。
例如:现在时间= 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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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))
答案 3 :(得分:0)
insert
into b
(select distinct name,
'notInTime'
from a
where sysdate not between a.time_start and a.time_end)