发布日期大于今天且小于到期日期的记录

时间:2012-10-02 11:58:38

标签: sql sql-server

我想要所有允许日期内的记录。

SELECT
  page_id, page_published_date, page_expired 
FROM 
  pages
WHERE
  ([page_published_date] <= getdate() OR [page_published_date] is null)
  AND
  ([csp_expired] <= getdate() OR [page_expired] is null)

请注意,日期可以包含空值。

示例表:

page_id, page_published_date, page_expired
1        2012-10-05           null
2        null                 2012-10-01
3        2012-08-01           2012-11-30

在这种情况下,正确的记录将是3。

2 个答案:

答案 0 :(得分:0)

SELECT
  page_id, page_published_date, page_expired 
FROM pages
WHERE
(
    [page_published_date] >= getdate()
    OR [page_published_date] is null
)
AND (
    [page_expired] <= getdate()
    OR [page_expired] is null
)

答案 1 :(得分:0)

根据选择#3作为唯一结果编辑答案

SELECT
  page_id, page_published_date, page_expired 
FROM 
  pages
WHERE
  -- Publication date BEFORE today (current time)
  ([page_published_date] <= getdate() OR [page_published_date] is null)
  AND
  -- and page has not expired
  (datediff(d,0,getdate()) < [page_expired] OR [page_expired] is null)

从主题行直接翻译

SELECT
  page_id, page_published_date, page_expired 
FROM 
  pages
WHERE
  -- Publication date greater than today
  ([page_published_date] > DateDiff(D,0,getdate()) OR [page_published_date] is null)
  AND
  -- and [Publication date?] less than the expiration date
  ([page_published_date] < [page_expired] OR [page_expired] is null)

注意:

  1. DateDiff(D,0,getdate())为您提供“今天”,即没有时间部分
  2. 我觉得你不想在今天比较[page_expired],因为今天在给出第一个条件的情况下预先设定[page_published_date]
  3. 如果我的解释错误,请使用我的翻译模式插入所需的任何更改