我在试图找出某些东西时遇到了一些困难,让我说我有一个日期和时间;
我想增加180分钟;
SELECT DATEADD(MINUTE,180,'2018-05-24 15:00')
这会给我回答“2018-05-24 18:00”,但我想在一个范围内进行,所以如果你在09:00 - 17:00之间添加分钟,那么这样的话;
SELECT DATEADD(MINUTES,180,'2018-05-24 15:00') WHERE '2018-05-24 15:00' BETWEEN '2018-05-24 09:00' AND '2018-05-24 17:00'
所以答案就是“2018-05-25 10:00”
答案 0 :(得分:1)
然而,这并不是特别漂亮......
USE Sandbox;
GO
CREATE TABLE Times (DateNTime datetime2(0));
INSERT INTO Times
VALUES ('20180520 10:00:00'),
('20180520 15:20:00'),
('20180521 09:32:00'),
('20180521 14:17:00'),
('20180522 16:54:00'),
('20180523 12:46:00'),
('20180524 15:32:00');
GO
SELECT *
FROM Times;
GO
SELECT T.DateNTime,
CASE WHEN CONVERT(time,T.DateNTime) <= '14:00' THEN DATEADD(MINUTE, 180,T.DateNTime)
ELSE DATEADD(MINUTE, 180 - DATEDIFF(MINUTE,T.DateNTime,DATEADD(HOUR,17,DATEADD(DAY, DATEDIFF(DAY, 0, T.DateNTime),0))), DATEADD(HOUR,9,DATEADD(DAY, DATEDIFF(DAY, 0, T.DateNTime) + 1,0))) END
FROM Times T;
GO
DROP TABLE Times;
答案 1 :(得分:1)
你可以试试这个:
$ ./getenv5
Hello.
Hello.
Hello.
Hello.
Hello.
Hello.
Hello.
Hello.
Hello.
Hello.
$ reps=3 msg="oh no" ./getenv5
oh no
oh no
oh no
$
答案 2 :(得分:1)
很难,但这适用于所有情况。此解决方案适用于任何数量的(正)分钟,结果将始终在参数化小时内,并添加相应的天数。
DECLARE @RangeHourStart INT = 9
DECLARE @RangeHourEnd INT = 17
DECLARE @MinutesToAdd INT = 120
DECLARE @Date DATETIME = '2018-05-24 15:00'
SELECT
FinalDate = CASE
WHEN -- When final hour exceeds the range hour
DATEPART(HOUR, @Date) * 60 +
DATEPART(MINUTE, @Date) +
@MinutesToAdd % ((@RangeHourEnd - @RangeHourStart) * 60) > @RangeHourEnd * 60
THEN
DATEADD(HOUR, -1 * (@RangeHourStart - 1),
DATEADD(DAY, 1,
DATEADD(MINUTE, @MinutesToAdd % ((@RangeHourEnd - @RangeHourStart) * 60),
DATEADD(
DAY,
@MinutesToAdd / ((@RangeHourEnd - @RangeHourStart) * 60),
@Date))))
ELSE
DATEADD(MINUTE, @MinutesToAdd % ((@RangeHourEnd - @RangeHourStart) * 60),
DATEADD(
DAY,
@MinutesToAdd / ((@RangeHourEnd - @RangeHourStart) * 60),
@Date))
END
我做到了,所以你不需要对任何价值进行硬编码。