2016-07-23 17 views
0

如何編寫查詢以告訴我如果指定日期(e.g. 2015-01-15)屬於下表中ANY'from_date'to_date'期間的範圍內?這裏有什麼特別的是我只需要返回一個ID。列與行之間的SQL檢查日期

id | from_date | to_date 
a | 2015-01-01 | 2015-01-30 
a | 2015-04-01 | 2015-04-30 

目前查詢:

select id, 
case when from_date <= '2015-01-15' 
    and to_date >= '2015-01-15' 
    then 'true' else 'false' end as status 
from dates 

當前的結果:

id | status 
a | true 
a | false 

期望的結果:

id | status 
a | true 
+0

你可以找到你所需要的:https://www.postgresql.org/docs/9.1/static/ functions-datetime.html – Sombriks

+2

你有沒有試圖寫這個?這是一個非常基本的SQL請求。請查看[如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)。關於Sombriks的建議,這是一個起點,但您需要的是'WHERE'子句中的[BETWEEN](http://www.postgresqltutorial.com/postgresql-between/)運算符。 –

+0

謝謝約翰,試圖改進這個例子。 – Kieran

回答

0
select id,'true' as status 
from dates 
where '2015-01-15' between from_date and to_date; 
+0

選擇x,東西和東西之間的東西謝謝切廷。但是,如果它是假的,我也想返回該ID。所以每個ID一行。 – Kieran

1

我猜你正在尋找的是DISTINCT ON。 id列上的DISTINCT ON每個ID只輸出一行。

嘗試下面的查詢,

select distinct on(id) id, 
case when from_date <= '2015-01-15' 
and to_date >= '2015-01-15' 
then 'true' else 'false' end as status from dates; 

其輸出到,

id | status 
    ----+-------- 
    a | true