2011-11-12 44 views
6

所以我下面的SELECT語句:結合來自不同模式的兩個SELECT語句「生成」結果到一個表

SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4) AS Decade 
FROM Movies M, Awards A 
WHERE {SOME WHERE CLAUSE} 
GROUP BY Decade; 

SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade 
FROM Awards A2 
WHERE {SOME WHERE CLAUSE} 
GROUP BY Decade; 

第一個是「生」的表與列(美國,十年),第二個是「生成」列的另一個表(總計,十年)。我想加入這兩個表,以便我得到一個表(美國,總計,十年)。我該怎麼做?

回答

16

把它們放在子查詢,並做了JOIN

SELECT a.US, a.decade, b.total FROM 

    (SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4) AS Decade 
    FROM Movies M, Awards A 
    WHERE {SOME WHERE CLAUSE} 
    GROUP BY Decade) AS a 

INNER JOIN 

    (SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade 
    FROM Awards A2 
    WHERE {SOME WHERE CLAUSE} 
    GROUP BY Decade) AS b 

ON a.decade = b.decade 
+1

只是一個小問題:我寧願不'SELECT *''但選擇a.US,a.DECADE,b.TOTAL'所以你贏了結果中不會得到DECADE兩次。 – tobiasbayer

+0

@CodeBrickie:是的,謝謝! – knittl

+0

這就像一個魅力:)謝謝! –

相關問題