如何在sql中显示半小时间隔的时间

时间:2012-10-12 05:16:35

标签: sql-server-2008

我正在使用SQL Server 2008,我有时间列(varchar),时间间隔为10分钟。我想以半小时为基础显示时间..

表格(timeslot)包含以下数据:

time
-----
11:10 AM
11:20 AM
11:30 AM
11:40 AM
11:50 AM
12:00 PM
12:10 PM
12:20 PM
12:30 PM
12:40 PM
12:50 PM
01:00 PM
01:10 PM
01:20 PM

我想显示这个输出:

time
-----
11:00 AM
11:30 AM
12:00 PM
12:30 PM
01:00 PM
01:30 PM

有人可以帮我这个吗?提前谢谢......

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT 
    (list of columns)
FROM 
    dbo.YourTableWithTheTime
WHERE 
    DATEPART(MINUTE, CAST(YourTimeColumnHere as TIME)) IN (0, 30)

当然 - 如果您首先在列中使用了TIME相应的数据类型,那么您可以自己保存CAST(.. as TIME)构造,事情会更容易....

更新:如果您需要按时间订购 - 请使用此功能:

SELECT 
    DISTINCT [time]
FROM 
    dbo.YourTableWithTheTime
WHERE 
    DATEPART(MINUTE, CAST([time] as TIME)) IN (0, 30)
ORDER BY
    CAST([time] as TIME)

PS:命名列time也是非常糟糕的主意 - 因为这是SQL Server 2008中的保留关键字(对于数据类型).....

答案 1 :(得分:0)

WITH CTE 
AS (SELECT DISTINCT columnname FROM table_name
WHERE DATEPART(MINUTE, CAST(column as TIME)) IN (0, 30) )
SELECT columnname
FROM CTE
ORDER BY CAST(columnname as time)