我正在使用SQL Server 2014,需要在CASE
语句中添加以下逻辑:
如果变量StayDate
在12月22日至12月31日期间,则分类为“ 1”;如果介于1月1日至1月6日之间,则分类为“ 2”,否则分类为“ 0”
StayDate
的数据类型为datetime
(例如:2017-12-15 00:00:00.000
)。
如何在CASE
语句中编写此逻辑?
答案 0 :(得分:4)
听起来好像您不在乎年份,而您希望年份在那儿处理可能跨越数年的数据。考虑到这一点:
select case when month(staydate) = 12 and day(staydate) >= 22 then 1
when month(staydate) = 1 and day(staydate) <= 6 then 2
else 0 end
答案 1 :(得分:2)
用例,如下所示,如果您需要两个单独的列
select case when StayDate between '2018-12-22' and '2018-12-31' then 1 end as classification_01
case when StayDate between '2019-01-01' and '2018-01-06' then 2 end as classification_02 from t
但是如果您只需要分类列,那么它将是 像下面一样
select case when StayDate between '2018-12-22' and '2018-12-31'
then 1
case when StayDate between '2019-01-01' and '2018-01-06'
then 2 else null
end as clssification from t
注意,如果您只需要比较月份,请遵循@joel解决方案
答案 2 :(得分:0)
SELECT
CASE WHEN StayDate between '2018-12-22' and '2018-12-31' THEN 1
WHEN StayDate between '2019-01-01' and '2018-01-06' THEN 2
ELSE 0
END as clasification
FROM YourTable