有一个像这样的表
empid questionid options 1 1 A 2 1 A 3 1 B 4 1 C
现在我需要这样的结果
questionid responseA responseB responseC 1 50% 25% 25%
答案 0 :(得分:0)
SELECT CAST(100/
( SELECT COUNT(*)
FROM your_Table as t2
WHERE t2.questionid = t1.questionid )
* COUNT(*) AS VARCHAR) + '%' AS 'Percent', OPTIONS, questionid
FROM your_Table as t1
--WHERE questionid = 2
GROUP BY OPTIONS, questionid
ORDER BY questionid;
这是一种可行的方法 (适用于SQL-Server但不确定它是否在MySql中执行)
答案 1 :(得分:0)
你可以PIVOT;
SELECT questionid, (A / total) * 100 responseA, (B / total) * 100 responseB, (C / total) * 100 responseC FROM (
SELECT T1.questionid, T1.options, T2.total
FROM the_tbl T1
INNER JOIN (SELECT questionid, CAST(COUNT(*) AS MONEY) AS total FROM the_tbl GROUP BY questionID) T2 ON T2.questionid = T1.questionid
) T
PIVOT (
COUNT(options) FOR options IN ([A], [B], [C])
) AS pvt
ORDER BY questionid
答案 2 :(得分:0)
T-SQL:
SELECT
questionid,
SUM(CASE options WHEN 'A' THEN 100.0 ELSE 0.0 END) / COUNT(options) AS responseA,
SUM(CASE options WHEN 'B' THEN 100.0 ELSE 0.0 END) / COUNT(options) AS responseB,
SUM(CASE options WHEN 'C' THEN 100.0 ELSE 0.0 END) / COUNT(options) AS responseC
FROM
answers
GROUP BY
questionid
注意:为避免转换和乘以100,我在100.0
表达式中使用了0.0
和CASE ... END
值。