2015-11-19 105 views
0

我想實現一個內連接來比較兩個表中的值,但是沒有出於某種原因,並在查詢返回零列。內連接有兩個選擇的sql

我有兩個表的安全性和security_his並試圖加入他們列SECURITY_ID和INVESTMENT_OBJECTIVE。查詢如下

SELECT * 
FROM SECURITY origin 
INNER JOIN (
    SELECT * 
    FROM SECURITY_HIS t2 
    WHERE DATED = (
      SELECT MAX(DATED) 
      FROM SECURITY_HIS t1 
      WHERE t1.SECURITY_ID = t2.SECURITY_ID 
      ) 
    ) history ON origin.SECURITY_ID = history.SECURITY_ID 
    AND origin.INVESTMENT_OBJECTIVE = history.INVESTMENT_OBJECTIVE; 
+2

應儘量將包括對SQL問題'SqlServer','MySql' RDBMS的標籤?某些功能不適用於所有數據庫。 –

+0

查詢看起來不錯,可能你沒有匹配的數據。檢查內部選擇的結果SELECT * FROM SECURITY_HIS t2 WHERE DATED =(' –

+0

它是sqlServer和我有匹配的數據!應該是有問題的查詢 – user1200279

回答

1
WITH cte as (
    SELECT S.*, 
      row_number() over 
       (partition by S.SECURITY_ID ORDER BY SH.DATED DESC) 
    FROM SECURITY S 
    JOIN SECURITY_HIS SH 
     ON S.SECURITY_ID = SH.SECURITY_ID 
    AND S.INVESTMENT_OBJECTIVE = SH.INVESTMENT_OBJECTIVE 
) 
SELECT * 
FROM cte 
WHERE rn = 1 
+0

返回0匹配:( – user1200279

+0

那麼問題是你的數據,你可以準備SQL小提琴http://sqlfiddle.com/我嗎? –

+0

我導出的數據,但由於某種原因,它給語法錯誤與出口 – user1200279

0

您對最內層查詢沒有GROUP BY,所以只有一個值,刷爆了整個表,則返回。但是您的查詢也可以簡化爲更容易理解:

SELECT origin.*, history.Dated 
FROM SECURITY origin 
INNER JOIN (
    SELECT 
     SECURITY_ID, 
     INVESTMENT_OBJECTIVE, 
     MaxDated = MAX(DATED) 
    FROM SECURITY_HIS t2 
    GROUP BY 
     SECURITY_ID, 
     INVESTMENT_OBJECTIVE 
) history ON origin.SECURITY_ID   = history.SECURITY_ID 
     AND origin.INVESTMENT_OBJECTIVE = history.INVESTMENT_OBJECTIVE 
+0

上MaxDated = MAX有語法錯誤(日期)ORA-00923:FROM關鍵字未找到預期 00923. 00000 - ? 「從關鍵字找不到預期的地方」 *原因: *動作: 行錯誤:7列:18 – user1200279

+0

@ user1200279:不要使用標籤'SQL-server'如果你的引擎是Oracle。然後。我無法閱讀您的想法或錯誤消息。 –