我有一个名为Timezone的表,数据如下:
Call_ID Start_Time
93856 2011-08-04 09:59:47.000
58796 2011-08-05 14:54:37.000
25489 2011-08-09 15:32:13.000
我希望输出为:
Call_ID Start_Time Interval
93856 2011-08-04 09:59:47.000 0930
58796 2011-08-05 14:54:37.000 1430
25489 2011-08-09 15:32:13.000 1530
我做了类似的事情:
Select Call_ID , Start_Time,
CASE WHEN DATEPART(minute,Start_Time)>30 THEN
RIGHT('0' + CAST(DATEPART(HOUR,Start_Time) AS VARCHAR),2) + '30'
ELSE
RIGHT('0' + CAST(DATEPART(HOUR,Start_Time) AS VARCHAR),2) + '00'
END
From Timezone
Group By Call_ID , Start_Time,
CASE WHEN DATEPART(minute,Start_Time)>30 THEN
RIGHT('0' + CAST(DATEPART(HOUR,Start_Time) AS VARCHAR),2) + '30'
ELSE
RIGHT('0' + CAST(DATEPART(HOUR,Start_Time) AS VARCHAR),2) + '00'
END
有更好的方法吗?
答案 0 :(得分:4)
select Call_ID,
Start_Time,
right(100+datepart(hour, Start_Time), 2)+
right(100+30*(datepart(minute, Start_Time)/30), 2) as Interval
from TimeZone
答案 1 :(得分:0)
不是更短,但肯定更整洁,而且演员阵容和字符串连接更少:
;WITH intervals(h) AS
(
SELECT TOP (48) CONVERT(TIME(0), DATEADD(MINUTE, 30*(number), '00:00'))
FROM master..spt_values
WHERE number >= 0
GROUP BY number
ORDER BY number
)
SELECT
t.Call_ID,
t.Start_Time,
Interval = REPLACE(CONVERT(VARCHAR(5), i.h), ':', '')
FROM intervals AS i
INNER JOIN dbo.TimeZone AS t
ON DATEDIFF(MINUTE, i.h, CONVERT(TIME(0), t.Start_Time)) BETWEEN 1 AND 30;
如果您在边界上有一个值,则不确定您想要做什么。你想让它落在当前的间隔还是以前的间隔?如果您想要不同的行为,可以将BETWEEN 1 AND 30
更改为BETWEEN 0 AND 29
。