连接没有公共列但与范围公式相关的表

时间:2016-05-01 06:21:14

标签: sql oracle jointable

我想加入两张桌子 表1有4列 -

ID   Name  Start_Date    End_date
1    John  20/dec/0009   15/Sep/0010 

表2有3列 -

Low High Frequency
1   50   Weekly
51  150  Monthly

在这里,我必须根据低和高范围报告频率,即End_date-start_date。我如何加入这两个? 无法弄清楚。提前谢谢!

2 个答案:

答案 0 :(得分:0)

这个怎么样:

SELECT Table1.ID, Table1.Name, Table2.Frequency 
FROM Table1 
  JOIN Table2 ON 
    Table2.Low >= DateDiff(d, Table1.End_Date, Table1.Start_Date) AND 
    Table2.High < DateDiff(d, Table1.End_Date, Table1.Start_Date)

答案 1 :(得分:0)

Oracle安装程序

CREATE TABLE table1 (ID, Name, Start_Date, End_date ) AS
SELECT 1, 'John', DATE '0009-12-20', DATE '0010-09-15' FROM DUAL; 

CREATE TABLE Table2 ( Low, High, Frequency ) AS
SELECT  1,   50, 'Weekly'  FROM DUAL UNION ALL
SELECT  51, 150, 'Monthly' FROM DUAL UNION ALL
SELECT 151, 730, 'Yearly'  FROM DUAL ;

<强>查询

SELECT *
FROM   table1 t1
       INNER JOIN
       table2 t2
       ON ( end_date - start_date BETWEEN LOW AND HIGH );

<强>输出

        ID NAME START_DATE          END_DATE                   LOW       HIGH FREQUENCY
---------- ---- ------------------- ------------------- ---------- ---------- ---------
         1 John 0009-12-20 00:00:00 0010-09-15 00:00:00        151        730 Yearly