SQL - 小时格式

时间:2017-03-21 10:57:18

标签: sql sql-server

我这里有我的sql case声明。

CASE WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') 
            and DATEPART(HOUR,dt.start_time) BETWEEN 7 AND 17 THEN '103856' --WEEKDAY
     WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') 
            and DATEPART(HOUR,dt.start_time) BETWEEN 17 AND 22 THEN '103857' --WEEKDAY-EVENING
    WHEN DATENAME(WeekDay, dt.start_time) IN ('Saturday', 'Sunday') THEN 'WEEKEND'  
END 

我如何格式BETWEEN 7 AND 17格式BETWEEN 7 AND 16:59:59

3 个答案:

答案 0 :(得分:3)

请勿使用function ViewModel () { var self = this; // ... self.allPossibleTags = [] self.selectAll = function(data, event){ self.selectedTags(self.allPossibleTags); } } // upon document.ready $(document).ready(function() { var viewModel = new ViewModel(); viewModel.allPossibleTags = $('.dataQueryRadioBtn').get().map(function(elm) { return elm.value }); ko.applyBindings(viewModel); }); ,而是使用DATEPART(HOUR,dt.start_time)

CAST(dt.start_time as time)

另外,我不会使用CASE WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') and CAST(dt.start_time as time) BETWEEN '07:00:00' AND '16:59:59' THEN '103856' --WEEKDAY WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') and CAST(dt.start_time as time) BETWEEN '17:00:00' AND '21:59:59' THEN '103857' --WEEKDAY-EVENING WHEN DATENAME(WeekDay, dt.start_time) IN ('Saturday', 'Sunday') THEN 'WEEKEND' END ,我会使用BETWEEN...AND<=

>=

Aaron Bertrand在他的文章"What do BETWEEN and the devil have in common?"

中解释得更好

答案 1 :(得分:2)

这是一种有效的方法。它不会转换为varchar来确定工作日,并且无论语言的本地设置如何都可以工作。

这会弄乱你当前的代码:

SET LANGUAGE Italian;  
SELECT DATENAME(weekday,'12/5/2007')

这会忽略语言设置:

SELECT CASE WHEN datediff(d, 0, dt.start_time)%7 < 5
     THEN 
       CASE WHEN DATEPART(HOUR,dt.start_time) BETWEEN 7 AND 16 
            THEN '103856' --WEEKDAY
     ELSE 
       -- not sure what you are trying to do here
       CASE WHEN DATEPART(HOUR,dt.start_time) BETWEEN 17 AND 22
            THEN '103857' --WEEKDAY-EVENING
       END
     END
ELSE 
  'WEEKEND'
END

答案 2 :(得分:1)

你只需要改变17到16,因为16:59:59的小时是16,而从17:00:00开始它是17。

CASE WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') 
            and DATEPART(HOUR,dt.start_time) BETWEEN 7 AND 16 THEN '103856' --WEEKDAY
     WHEN DATENAME(WeekDay, dt.start_time) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') 
            and DATEPART(HOUR,dt.start_time) BETWEEN 17 AND 22 THEN '103857' --WEEKDAY-EVENING
    WHEN DATENAME(WeekDay, dt.start_time) IN ('Saturday', 'Sunday') THEN 'WEEKEND'  
END 

如果您想要从17:00:00到21:59:59过滤时间范围,您还需要更改表达式之间的第二个。