2012-11-22 140 views
1

我有数据表包含的问题数量和响应数据。获得组内计数和百分比

我需要能够得到的答复计数对每个问题的每个选项,也表示有多大比例。

例如数据可能看起来像

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 

查询得到的结果,我可以做查询来获取每个响应的计数但没有看到获得百分比的方法。

任何人都可以在这里帮助吗?

非常感谢

+0

请参阅http://stackoverflow.com/questions/8753388/how-can-i-get-the-percentage-of-total-rows-with-mysql-for-a-group使用'CROSS JOIN '针对只返回未分组COUNT(*)'的子查询,您可以将当前组的COUNT()分成该总值。 –

+0

另外这个人的答案是更清晰一点阅读:http://stackoverflow.com/questions/8768625/calculation-of-percentage-of-group-count –

回答

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 
+0

很抱歉的延迟响应,但感谢您的解决方案。 – Dave

+0

不客气dave':D' –