SQL根据日期选择行

时间:2014-09-18 02:17:30

标签: 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-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中给定的“日期”和“名称”,请浏览表2并获取所有具有相同“名称”并且日期为“日期”(表1)和5之前10天的行“日期”之后的几天(见表1)。
  3. 因此,对于Table1,“Alex”在“2014-02-08”上,我想抓住Table2中所有也说“Alex”的行,但其日期在“2014-01-29”之间(10天前) 2014-02-08)和“2014-02-13”(2014-02-08之后的5天)。

    对于“2014-06-15”中的“Bob”,我想抓住Table2中所有也说“Bob”的行,但其日期在“2014-06-05”之间(2014-06-之前的10天) 15)和“2014-06-20”(2014-06-15之后的5天)。

    预期输出为:

    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
    

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

2 个答案:

答案 0 :(得分:0)

我认为你可以这样做:

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'
             );

答案 1 :(得分:0)

请参阅:

http://sqlfiddle.com/#!4/82e1e/10

假设甲骨文,但你得到了图片:-)。您需要在结果中格式化日期。这留给你细读。

如果上面的链接无法打开,则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;

结果是:

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
相关问题