需要帮助才能完成加入

时间:2013-04-03 12:09:47

标签: sql join

当前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()去了哪里。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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;