我写了SQL,但它给出了一个错误

时间:2014-09-11 05:49:37

标签: mysql sql count percentage

我想知道2012年夏季学期在不同地点的年龄大于5岁的人的百分比。我写了SQL,但它给出了一个错误。我没有发现错误。请有人帮帮我

SELECT Venue,
100*COUNT
    (SELECT DISTINCT hid,
    q1 FROM raw_data 
    WHERE q2 > 5 
    AND Year=2012 
    AND Semester='summer' 
    GROUP BY Venue)
    /(SELECT DISTINCT hid,q1 
     FROM raw_data 
     WHERE Year=2012 
     AND Semester='summer' 
     GROUP BY Venue) 
AS "%" 
FROM raw_data 
WHERE Year=2012 
AND Semester='summer' 
GROUP BY Venue

1 个答案:

答案 0 :(得分:1)

SELECT t2.Venue, 100*IFNULL(t1.ct, 0)/t2.ct AS '%'
FROM (
    SELECT Venue, COUNT(DISTINCT hid, q1) AS ct
    FROM raw_data 
    WHERE q2 > 5
    AND Year = 2012
    AND Semester = 'summer'
    GROUP BY Venue) AS t1
RIGHT JOIN (
    SELECT Venue, COUNT(DISTINCT hid, q1) AS ct
    FROM raw_data
    WHERE Year = 2012
    AND Semester = 'summer'
    GROUP BY Venue) AS t2
ON t1.Venue = t2.Venue

我使用RIGHT JOIN,因此我们会为没有超过5岁的人提供0%