SQL根据日期选择行

SQL根据日期选择行,sql,join,netezza,Sql,Join,Netezza,我有两张表表表1和表2: 表1 Date Name Other 2014-02-08 Alex 1 2014-06-15 Bob 1 表2 Date Name Count 2014-02-07 Alex 1 2014-01-31 Alex 2 2014-02-09 Alex 4 2014-02-08 Alex 10 2014-02-10 Alex 0 2014-02-

我有两张表表表1和表2:

表1

Date          Name   Other
2014-02-08    Alex   1
2014-06-15    Bob    1
表2

Date          Name    Count
2014-02-07    Alex    1
2014-01-31    Alex    2
2014-02-09    Alex    4
2014-02-08    Alex    10
2014-02-10    Alex    0
2014-02-01    Alex    4
2014-01-08    Alex    5
2014-03-08    Alex    4
2014-06-01    Bob     22
2014-06-02    Bob     0
2014-06-10    Bob     9
2014-06-15    Bob     3
2014-06-16    Bob     3
2014-06-20    Bob     5
2014-06-14    Bob     18
2014-07-11    Bob     1
2014-08-15    Bob     2
我很难构建一个查询来完成以下任务:

从表1中,浏览每个日期和名称 对于表1中给定的日期和名称,遍历表2并获取所有名称相同且日期在表1中日期前10天和表1中日期后5天的行。 所以,对于表1,2014-02-08上的Alex,我想抓住表2中的所有行,这些行也表示Alex,但其日期介于2014-02-08之前10天的2014-01-29和2014-02-08之后5天的2014-02-13之间

对于2014-06-15上的Bob,我想抓住表2中的所有行,这些行也表示Bob,但其日期介于2014-06-15之前10天的2014-06-05和2014-06-15之后5天的2014-06-20之间

预期产出为:

Date          Name    Count
2014-02-07    Alex    1
2014-01-31    Alex    2
2014-02-09    Alex    4
2014-02-08    Alex    10
2014-02-10    Alex    0
2014-02-01    Alex    4
2014-06-10    Bob     9
2014-06-15    Bob     3
2014-06-16    Bob     3
2014-06-20    Bob     5
2014-06-14    Bob     18

在我的实际工作中,表1中的行数要大得多,并且我希望在参考日期之前/之后获取的天数可能会有所不同。

我认为您可以这样做:

select t2.*
from table1 t2
where exists (select 1
              from table1 t1
              where t1.name = t2.name and t1.date >= t2.date - 'interval 10 day' and
                    t1.date <= t2.date + 'interval 10 day'
             );
见:

假设是甲骨文,但你明白了。您需要在结果中设置日期的格式。这是留给你阅读的

如果无法打开上述链接,则sql为:

select t2.*
from
  table2 t2, table1 t1
where
  t1.name = t2.name
  and t2.date1 > t1.date1 -10 
  and t2.date1 <= t1.date1 +5;

有什么问题吗?你被困在哪里了?这是MySQL还是MS SQL?@PM 77-1:我只看过基本的SQL教程,只处理过单个表。目前我还不明白处理两个表的逻辑。@Rajesh:正如标签中所述,Netezza SQL。现在是时候学习更难的教程了。OP操作两个不同的表:表1和表2。@Gordon Linoff:对不起,我对SQL完全陌生。我想我得到了大部分查询,假设它是有效的语法,我必须查找它,但是select 1是什么意思呢?select 1将返回1。当我们只需要检查匹配记录的存在性,因此不需要获取任何字段时,就可以使用它。它通常与EXISTS子句一起使用。@Gordon Linoff:查询是否应该从表2 t2而不是表1 t2中选择t2.*?或者,真的,表1和表2。。。
select t2.*
from
  table2 t2, table1 t1
where
  t1.name = t2.name
  and t2.date1 > t1.date1 -10 
  and t2.date1 <= t1.date1 +5;
DATE1                           NAME    COUNT
February, 07 2014 00:00:00+0000 Alex    1
January, 31 2014 00:00:00+0000  Alex    2
February, 09 2014 00:00:00+0000 Alex    4
February, 08 2014 00:00:00+0000 Alex    10
February, 10 2014 00:00:00+0000 Alex    0
February, 01 2014 00:00:00+0000 Alex    4
June, 10 2014 00:00:00+0000     Bob     9
June, 15 2014 00:00:00+0000     Bob     3
June, 16 2014 00:00:00+0000     Bob     3
June, 20 2014 00:00:00+0000     Bob     5
June, 14 2014 00:00:00+0000     Bob     18