我有这个表结构:
CREATE TABLE TIMETABLE
([ID] int, [Name] varchar(50), [StartDate] datetime, [EndDate] datetime)
;
INSERT INTO TIMETABLE
([ID], [Name], [StartDate], [EndDate])
VALUES
(1, 'John', '2017-01-29 16:00:00.000', '2017-01-29 16:12:00.000'),
(2, 'Mario', '2017-01-29 16:17:00.000', '2017-01-29 16:29:00.000'),
(3, 'Kate', '2017-01-15 10:35:00.000', '2017-01-15 10:40:00.000'),
(4, 'Maria', '2017-01-15 10:17:00.000', '2017-01-15 10:27:00.000'),
(5, 'Oliver', '2017-01-15 13:46:00.000', '2017-01-29 14:00:00.000')
;
结果如下:
select * from TIMETABLE
ID Name StartDate EndDate
1 John 2017-01-29T16:00:00Z 2017-01-29T16:12:00Z
2 Mario 2017-01-29T16:17:00Z 2017-01-29T16:29:00Z
3 Kate 2017-01-15T10:35:00Z 2017-01-15T10:40:00Z
4 Maria 2017-01-15T10:17:00Z 2017-01-15T10:27:00Z
5 Oliver 2017-01-15T13:46:00Z 2017-01-29T14:00:00Z
我想知道日期范围为15分钟的范围,例如:
ID Name StartDate EndDate HourRangeTime
1 John 2017-01-29T16:00:00Z 2017-01-29T16:12:00Z 16:00
在示例中,startdate和enddate在16:00到16:12之间,范围是16:00
结果应该是这样的:
ID Name StartDate EndDate HourRangeTime
1 John 2017-01-29T16:00:00Z 2017-01-29T16:12:00Z 16:00
2 Mario 2017-01-29T16:17:00Z 2017-01-29T16:29:00Z 16:15
3 Kate 2017-01-15T10:35:00Z 2017-01-15T10:40:00Z 10:30
4 Maria 2017-01-15T10:17:00Z 2017-01-15T10:27:00Z 10:15
5 Oliver 2017-01-15T13:46:00Z 2017-01-29T14:00:00Z 13:45
如何填写HourRangeTime列,记录日期并查看它属于哪个范围?
答案 0 :(得分:4)
您似乎专注于StartDate
。
执行此操作的相对一般方法是将其转换为分钟,然后将分钟截断为最接近的15分钟。这是代码:
select cast(dateadd(minute,
15 * (datediff(minute, 0,
cast(StartDate as time)
) / 15
), 0
) as time)
这会将结果作为time
返回。
答案 1 :(得分:1)
您可以获得差异并处理未来。
SELECT StartTime, EndTime, DATEDIFF(MINUTE, StartTime , EndTime) AS MinuteDiff
FROM TIMETABLE
答案 2 :(得分:1)
您可以尝试这个以获得所需的输出:
SELECT
CONCAT(DATEPART(hh,StartDate), ':',
CASE
WHEN DATEPART(MINUTE,StartDate) BETWEEN 0 AND 14 THEN '00'
WHEN DATEPART(MINUTE,StartDate) BETWEEN 15 AND 29 THEN '15'
WHEN DATEPART(MINUTE,StartDate) BETWEEN 30 AND 44 THEN '30'
WHEN DATEPART(MINUTE,StartDate) BETWEEN 45 AND 59 THEN '45'
ELSE '00'
END) AS HourRangeTime
FROM TIMETABLE
输出:
HourRangeTime
-------------
16:00
16:15
10:30
10:15
13:45
答案 3 :(得分:1)
你可以使用它。
SELECT *,
CONVERT(VARCHAR,DATEPART(HOUR, [StartDate]))
+ ':'
+ RIGHT(CONVERT(VARCHAR,(DATEPART(MINUTE, [StartDate]) / 15) * 15)+'0',2) HourRangeTime FROM TIMETABLE