2016-05-01 39 views
-5

我要加入兩個表相關 表1具有4 columns-加入而不公用列表,但與範圍式

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

表2具有3 columns-

Low High Frequency 
1 50 Weekly 
51 150 Monthly 

在這裏,我有根據End_date-start_date的Low和High範圍報告頻率。我如何加入這兩個? 找不出來。提前致謝!

+0

兩個日期之間的天差是否爲'1'低和'50'高? –

+0

也** TAG **您正在使用的'DBMS',因爲查詢需要'DATE'函數,這與每個供應商有所不同 –

+0

「兩個日期之間的天差是1還是50高?是的,它是Oracle。 – Geet

回答

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) 
+0

謝謝,但這並不奏效。完成新的SQL。 – Geet

+0

DATEDIFF函數特定於SQL Server。我相信你只需要找到Oracle的等價物。 – cChacon

0

甲骨文設置

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