0

こんにちは、次のフィールドを持つテーブルがあります。

person
from_dt
to_dt
house_num

人が住んでいた番地を記述し、from_dt と to_dt を提供します。from_dt は 2000-01-01 にさかのぼり、to_dt は 2012-01-01 にさかのぼります。

質問:

2004 年から 2009 年の間に住んでいた人だけを選びたいと思います。

つまり、次のような人を除外します

person  from_dt     to_dt       house_num
-----------------------------------------
dave    2000-01-01  2002-01-01  34

ただし、次のような人を維持してください:

person  from_dt     to_dt       house_num
-----------------------------------------
susan   2008-01-01  2009-06-01  93

ここのロジックに問題があります。from_dt と to_dt を使用して、2009 年に 1 日以上家に住んでいた人だけを含める方法について誰か提案はありますか?

どうもありがとう。

4

1 に答える 1

1

テストされていないため、タイプミスがある可能性がありますが、ここにアイデアがあります- from は範囲内にある必要があります。

select * 
from table
where (year(from_dt) < 2009 and year(from_dt) > 2004) 
   or (year(to_dt) < 2009 and year(to_date) > 2004)
   or (year(from_dt) < 2004) and year(to_date) > 2009)

NOT both before または both after をテストすることもできます。

select *
from table
where not ((year(from_date) < 2004 and year(to_dt) < 2004)
         or(year(from_date) > 2009 and year(to_dt) > 2009))

または(ニコラが指摘したように)

select * 
from table
where year(from_dt) <= 2009 and year(to_dt) >= 2004
于 2013-03-08T11:09:35.127 に答える