[英]SQL: DATEDIFF If Start Date is greater than a date in another field
I'm looking to work out the difference between 2 dates that I have declared as variables, 我正在寻找算出我声明为变量的2个日期之间的差异,
DECLARE @start_date DATETIME
SET @start_date= '20000728'
DECLARE @end_date DATETIME
SET @end_date= '20161028'
But only if @start_date is greater than DATE_CREATED. 但仅当@start_date大于DATE_CREATED时。 If it is not I want to do the difference between DATE_CREATED and @end_date
如果不是,我想做DATE_CREATED和@end_date之间的区别
How can I go about doing this? 我该怎么做呢?
All I have at the moment is: 我目前所拥有的是:
DATEDIFF(DAY, @start_date, @end_date) AS 'DAYS_AVAIL_RANGE'
I'm not sure how I go about incorporating an IF statement to do this, 我不确定如何合并IF语句来做到这一点,
Any help is appreciated, cheers! 感谢您的帮助,干杯!
Try this. 尝试这个。 This will definitely solve your problem as here casting is performed for date/time value.
这肯定会解决您的问题,因为此处将执行日期/时间值的转换。
select
case when DATEDIFF(day,convert(date,DATE_CREATED),CONVERT(date,@start_date)) > 0
then datediff(DAY, convert(date,@start_date), convert(date,@end_date))
else
datediff(DAY, convert(date,DATE_CREATED), convert(date,@end_date))
end
You want case
: 您想要的
case
:
select (case when @start_date > date_created
then datediff(DAY, @start_date, @end_date)
else datediff(DAY, date_created, @end_date)
end) as days_avail_range
尝试这个
select datediff(DAY, (select max(v) from (VALUES (@start_date), (DATE_CREATED)) as value(v)) , @end_date) from yourtable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.