正确的if语句,并在这种情况下,在SQL Server
问题描述:
我在我的数据库得到这个数据正确的if语句,并在这种情况下,在SQL Server
id shift_no time_in time_out
---------------------------------------
1 Shift 1 06:00:00 14:00:00
2 Shift 2 14:00:00 22:00:00
3 Shift 3 22:00:00 06:00:00
所以我得到了这个日期:
convert(time(0),dateadd(HOUR, 15, getdate()), 108)
我想只得到转变,是这个时间转换的范围内(时间(0),DATEADD(HOUR,15,GETDATE()),108)
答
对不起,我不能评论还有尚未...这是Tanner回答的评论。
你可以尝试分裂3班次项:
INSERT INTO #shifts
(
shiftNo,
time_In,
time_Out
)
VALUES
(1, '06:00:00', '14:00:00'),
(2, '14:00:00', '22:00:00'),
(3, '22:00:00', '23:59:59'),
(3, '00:00:00', '06:00:00');
-- the selected time
SELECT CONVERT(TIME(0), DATEADD(HOUR, 15, GETDATE()), 108);
-- filter your shifts
SELECT *
FROM #shifts AS s
WHERE CONVERT(TIME(0), DATEADD(HOUR, -6, GETDATE()), 108)
BETWEEN s.time_In AND s.time_Out;
DROP TABLE #shifts;
答
select
*
from yourtable
where
time_in between getdate() and convert(time(0),dateadd(HOUR, 15, getdate()), 108)
or time_out between getdate() and convert(time(0),dateadd(HOUR, 15, getdate()), 108)
答
可以使用BETWEEN
与您的进出时间,像这样(注意下面的重新运行的):在查询工作了
CREATE TABLE #shifts
(
shiftNo INT,
time_In TIME(0),
time_Out TIME(0)
);
INSERT INTO #shifts
(
shiftNo,
time_In,
time_Out
)
VALUES
(1, '06:00:00', '14:00:00'),
(2, '14:00:00', '22:00:00'),
(3, '22:00:00', '06:00:00');
-- the selected time
DECLARE @selectedTime TIME(0) = CONVERT(TIME(0), DATEADD(HOUR, 12, GETDATE()), 108);
-- modify the selected time if it falls in the shift that crosses midnight
SET @selectedTime = CASE WHEN @selectedTime > '22:00:00' OR @selectedTime < '06:00:00'
THEN '22:01:00' -- modified value
ELSE @selectedTime -- regular value
END;
-- show the time we are working with
SELECT @selectedTime;
-- filter your shifts
SELECT *
FROM #shifts AS s
WHERE @selectedTime
BETWEEN s.time_In AND CASE WHEN s.time_Out = '06:00:00' -- is the out time 6.00
THEN '23:59:59' -- change it to before midnight if so
ELSE s.time_Out -- keep the time as it is
END;
DROP TABLE #shifts;
的CASE
语句,如果你是@selectedTime
工作时间是将s.time_Out
之前跨越午夜时间它们都被调整,这允许选择最后一班。
有可能是一个更简单的解决方案,但这与您提供的数据一起工作。
我可以尝试这件事情,这将是好的!谢谢:) – GGw
这可能会工作,但取决于高度紧密,你的源数据必然会出现这些变化,看起来像是你可以解决的问题的解决方法。我稍后再试 – Tanner