Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL中有条件地用另一个日期替换日期?_Sql_Sql Server - Fatal编程技术网

如何在SQL中有条件地用另一个日期替换日期?

如何在SQL中有条件地用另一个日期替换日期?,sql,sql-server,Sql,Sql Server,我有一个数据集,有很多日期范围。我想构建一个代码,只允许我选择,比如说,过去30天的天数。但是,我希望截断或排除范围开始前的天数 假设我的数据集是这样的: StayID StayStart StayEnd 1 Jan 1 Jan 10 2 Jan 1 Feb 28 3 Feb 1 Feb 10 4 Feb 10 Feb 28 我还有一个参数{?ReportStart},假设我将它设置为2月1日。首先,我将排除在此之前的所有停

我有一个数据集,有很多日期范围。我想构建一个代码,只允许我选择,比如说,过去30天的天数。但是,我希望截断或排除范围开始前的天数

假设我的数据集是这样的:

StayID StayStart StayEnd
1      Jan 1     Jan 10
2      Jan 1     Feb 28
3      Feb 1     Feb 10
4      Feb 10    Feb 28
我还有一个参数{?ReportStart},假设我将它设置为2月1日。首先,我将排除在此之前的所有停留,但我还想修改日期,以便所有日期都在选定范围之后。我想要以下输出:

StayID StayStart StayEnd
2      Feb 1     Feb 28
3      Feb 1     Feb 10
4      Feb 10    Feb 28
我想我应该这样做,但我对SQL非常陌生:

SELECT StayID, 
(SELECT CASE WHEN StayStart < {?ReportStart} THEN {?ReportStart}
    ELSE StayStart
    END
    ) AS StayStart,
StayEnd
选择statyid,
(在StayStart<{?ReportStart}然后{?ReportStart}时选择大小写)
艾尔斯泰斯特酒店
结束
)作为斯塔斯特,
住宿者

我走对了吗?任何建议都将不胜感激

您似乎想要:

select stayId,
       (case when StayStart < {?ReportStart} then {?ReportStart} else StayStart end) as StayStart,
       StayEnd
from t
where stayEnd > {?ReportStart};

使用您正在使用的数据库标记您的问题。使用SQL Server,这样看起来就不需要使用best()了。谢谢你的信息!
select stayId,
       greatest({?ReportStart}, StayStart) as StayStart,
       StayEnd
from t
where stayEnd > {?ReportStart};