2016-07-23 8 views
0

指定された日付(e.g. 2015-01-15)がANY 'from_date' 'to_date'の期間内にあるかどうかを教えてください。ここで特別なのは、IDごとに1行しか返されないということです。列と行の間の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

ありがとうございました。しかし、それが偽であればidを返すようにしたい。 1行につき1行です – Kieran

1

あなたが探しているのは、DISTINCT ONです。 id列のDISTINCT ONはIDごとに1つの行のみを出力します。

あなたがここで必要なものを見つけることができますに出力

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