2010-05-11 141 views
1

傢伙有什麼不對的SQL查詢:MySQL的GROUP BY和加入

$sql = "SELECT 
    res.Age, 
    res.Gender, 
    answer.*, 
    $get_sum, 
    SUM(CASE WHEN res.Gender='Male' THEN 1 else 0 END) AS males, 
    SUM(CASE WHEN res.Gender='Female' THEN 1 else 0 END) AS females 
    FROM Respondents AS res 
    INNER JOIN Answers as answer 
     ON answer.RespondentID=res.RespondentID 
    INNER JOIN Questions as question 
     ON answer.Answer=question.id 
    WHERE answer.Question='Q1' 
    GROUP BY res.Age 
    ORDER BY res.Age ASC"; 

的$ get_sum是SQL語句的排列從另一個表導出:

$sum[]= "SUM(CASE WHEN answer.Answer=".$db->f("id")." THEN 1 else 0 END) AS item".$db->f("id"); 
$get_sum = implode(', ', $sum); 

以上返回查詢這些值:

Age: 20  
    item1 0 
    item2 1 
    item3 1 
    item4 1 
    item5 0 
    item6 0 
Subtotal for Age 20  3 

Age: 24  
    item1 2 
    item2 2 
    item3 2 
    item4 2 
    item5 1 
    item6 0 
Subtotal for Age 24  9 

它應該返回:

Subtotal for Age 20  1 
Subtotal for Age 24  2 

在我的樣本數據中有3位受訪者,其中2位24歲,另一位20歲。 我想每個年齡的受訪者總數。

+0

請嘗試將您的查詢降低到最低限度。同時顯示sql-query的結果!我假設你的結果來自你的應用程序? – lexu 2010-05-11 04:56:14

回答

0
$sql = "SELECT 
    res.Age, 
    COUNT(1) AS SubTotalRespondentsByAge 
    $get_sum, 
    SUM(CASE WHEN res.Gender='Male' THEN 1 else 0 END) AS males, 
    SUM(CASE WHEN res.Gender='Female' THEN 1 else 0 END) AS females 
    FROM Respondents AS res 
    INNER JOIN Answers as answer 
     ON answer.RespondentID=res.RespondentID 
    INNER JOIN Questions as question 
     ON answer.Answer=question.id 
    WHERE answer.Question='Q1' 
    GROUP BY res.Age 
    ORDER BY res.Age ASC" 

您不能在select子句中包含與年齡具有多對一關係的任何列。我已經刪除了res.genderanswers.*列。你想要的是計數(1)的組(因爲你按res.Age分組)。