获得组内的计数和百分比

时间:2012-11-22 13:32:49

标签: mysql sql

我有一个包含问题编号和响应数据的数据表。

我需要能够获得每个问题的每个选项的响应计数,以及代表的百分比。

例如数据可能看起来像

questionNum   ResponseNum
1             1
1             2
1             2
1             2
1             3
2             1
2             1
2             2

....然后应该从

的查询中得到一个结果
questionNum     responseNum   count   percent
1               1             1       20
1               2             3       60
1               3             1       20
2               1             2       66
2               2             1       33

我可以执行查询以获取每个响应的计数,但看不到获取百分比的方法。

有人可以帮忙吗?

非常感谢

1 个答案:

答案 0 :(得分:4)

SELECT a.questionNum, a.responseNum,
        COUNT(*) `count`,
        (COUNT(*) / b.totalCOunt) * 100 Percentage
FROM   table1 a
       INNER JOIN 
        (
          SELECT questionNum, COUNT(*) totalCOunt
          FROM table1
          GROUP BY questionNum
        ) b ON a.questionNUm = b.questionNum
GROUP BY questionNum, responseNum

您还可以添加其他功能FLOOR

SELECT a.questionNum, a.responseNum,
        COUNT(*) `count`,
        FLOOR((COUNT(*) / b.totalCOunt) * 100) Percentage
FROM   table1 a
       INNER JOIN 
        (
          SELECT questionNum, COUNT(*) totalCOunt
          FROM table1
          GROUP BY questionNum
        ) b ON a.questionNUm = b.questionNum
GROUP BY questionNum, responseNum