2015-04-16 71 views
0

例如說你有以下SQL:SQL設置和使用變量在SELECT語句

SELECT 
    attempt.user_id, 
    attempt.team_id, 
    SUM(CASE 
     WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN attempt.score 
    END)/COUNT(CASE 
     WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN 1 
    END) as avg_score, 
    (SELECT 
      COUNT(atha.academy_module_id) 
     FROM 
      academy_team_has_academy_module atha 
     WHERE 
      atha.academy_team_id = attempt.team_id 
    ) as num_modules 

FROM 
    academy_attempt attempt 
GROUP BY attempt.user_id 

現在你想使用num_modules做以下動作:

num_modules/COUNT(attempt.module_id) as completed 

當我運行這個我得到(如預期)Unknown column num_modules

那麼有什麼辦法,我可以將它設置爲一個變量,所以我可以使用的價值?

回答

1

可以更改

(SELECT 
     COUNT(atha.academy_module_id) 
    FROM 
     academy_team_has_academy_module atha 
    WHERE 
     atha.academy_team_id = attempt.team_id 
) as num_modules 

@num_modules:=(SELECT 
     COUNT(atha.academy_module_id) 
    FROM 
     academy_team_has_academy_module atha 
    WHERE 
     atha.academy_team_id = attempt.team_id 
) as num_modules 

,然後你可以使用@num_modules後記作爲varible。

就像@num_modules/COUNT(attempt.module_id) as completed

+0

謝謝您的回答。你可以向我解釋爲什麼這不能用於創建視圖:(? –

+0

@MarcRasmussen我認爲這將有助於。[[http://stackoverflow.com/a/5331792/3020810]] – amow

1

我認爲要做到這一點的方法是做一個子查詢是這樣的:

SELECT 
    tbl.user_id, 
    tbl.team_id, 
    tbl.num_modules/tbl.countModule_id as completed, 
    tbl.avg_score, 
    tbl.num_modules 
FROM 
(
    SELECT 
     attempt.user_id, 
     attempt.team_id, 
     SUM(CASE 
      WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN attempt.score 
     END)/COUNT(CASE 
      WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN 1 
     END) as avg_score, 
     (SELECT 
       COUNT(atha.academy_module_id) 
      FROM 
       academy_team_has_academy_module atha 
      WHERE 
       atha.academy_team_id = attempt.team_id 
     ) as num_modules, 
     COUNT(attempt.module_id) as countModule_id 
    FROM 
     academy_attempt attempt 
    GROUP BY attempt.user_id 
) as tbl 
相關問題