2013-04-03 83 views
0

當前SELECT查詢需要幫助辦成一個加入

SELECT a.*, ROUND(((a.avg-b.avg)/b.avg)*100,2) pct_change 
FROM 
    ( 
    SELECT x.*, COUNT(*) rank 
    FROM blavg x 
     JOIN blavg y 
      ON y.bline_id = x.bline_id 
      AND y.id >= x.id 
    GROUP BY x.id 
) a 
JOIN 
( 
    SELECT x.*, COUNT(*) rank 
    FROM blavg x 
     JOIN blavg y 
      ON y.bline_id = x.bline_id 
      AND y.id >= x.id 
    GROUP BY x.id 
) b 
    ON b.bline_id = a.bline_id 
    AND b.rank = a.rank+1 
WHERE a.rank = 1; 

我想也

SELECT bl_id, bline FROM bl 
bl.bl_id = blavg.bline_id 

我已經試過

SELECT bl_id, bline 
FROM bl bl 
    LEFT JOIN ON bl.bl_id = blavg.bline_id 

但不知道我是否有正確的語法,我不確定在哪裏添加ON以及parens()去哪裏。

任何幫助將不勝感激。

+0

你得到什麼錯誤? – Deruijter

回答

0

所以你正在做某種查詢來檢索兩次兩次的行並做一些數學。
幸運的是,您的查詢已經返回bline_id您需要鏈接到您的bl表。

所以,你只需要在你的結果多了一個聯合檢索bl.bline領域,你需要:

SELECT bl.bline, a.*, ROUND(((a.avg-b.avg)/b.avg)*100,2) pct_change 
FROM 
    ( 
    SELECT x.*, COUNT(*) rank 
    FROM blavg x 
     JOIN blavg y 
      ON y.bline_id = x.bline_id 
      AND y.id >= x.id 
    GROUP BY x.id 
) a 
JOIN 
( 
    SELECT x.*, COUNT(*) rank 
    FROM blavg x 
     JOIN blavg y 
      ON y.bline_id = x.bline_id 
      AND y.id >= x.id 
    GROUP BY x.id 
) b 
    ON b.bline_id = a.bline_id 
    AND b.rank = a.rank+1 
    LEFT OUTER JOIN bl 
     ON bl.bl_id = a.bline_id 
WHERE a.rank = 1; 
+0

@ScorpiO - 那好像太明顯了!它的工作非常完美,非常感謝你! – bech64