我的桌子上有两条记录:
表格
ID StartDate EndDate
1 2013-01-01 2016-01-01
2 2016-02-01 NULL
我的查询:
@DatePeriodFrom = 2016-01-01
@DatePeriodTo = 2016-01-01
select *
from tableabove ta
where (ta.StartDate >= @DatePeriodFrom and ta.EndDate >= @DatePeriodTo)
我的问题是它不会返回任何结果。如果我将and
替换为or
,则会返回两行。我正在考虑使用ISNULL
但我没有运气。
修改
我想要的是根据给定的开始日期和结束日期返回行,无论该行是否具有空结束日期。
在上面的例子中,应该返回第一行。
在此示例中,应返回第二行:
@DatePeriodFrom = 2016-02-01
@DatePeriodTo = 2016-02-01
有什么想法吗?
答案 0 :(得分:1)
select *
from tableabove ta
where ta.StartDate <= @DatePeriodFrom and (ta.endDate is NULL or ta.EndDate >= @DatePeriodTo)
输出:Table values
答案 1 :(得分:1)
首先,我认为您使用@DatePeriodTo&lt; = ta.EndDate,而不是&#39;&gt; =&#39;。
假设startdate不能为null,条件应为:
where ta.StartDate >= @DatePeriodFrom
and (ta.EndDate is null or ta.EndDate <= @DatePeriodTo)
即使不适用于这种情况,还有一个问题...检查列类型是否仅包含日期或日期和时间... 31.12.2010 10:00 PM&gt; &#39; 31.12.2010&#39;
答案 2 :(得分:1)
再次:
案例A) 我想要那些“活着”的记录。在整个期间:
where ta.StartDate <= @DatePeriodFrom
and (ta.EndDate is null or ta.EndDate >= @DatePeriodTo)
案例B) 我想要在期间创建和结束的记录
where ta.StartDate >= @DatePeriodFrom
and (ta.EndDate <= @DatePeriodTo)
案例C) 我想要在我的时期内活着的记录:
where ta.StartDate <= @DatePeriodTo
and (ta.EndDate is null or ta.EndDate >= @DatePeriodFrom)
答案 3 :(得分:0)
如果您需要找到所有期间的交叉点:
where ta.StartDate <= @DatePeriodTo
and (ta.endDate IS NULL or ta.endDate >= @DatePeriodFrom)