这个SQL查询出了什么问题:
$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 :(得分: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子句中包含与age具有多对一关系的任何列。因此,我删除了res.gender
和answers.*
列。你想要的是计数(1)组(因为你按res.Age分组)。