以下是使用 MySQL 查询的方法:
select id,
sum(case when `1` = 'A' then 1 else 0 end) as CountA,
sum(case when `1` = 'B' then 1 else 0 end) as CountB,
sum(case when `1` = 'C' then 1 else 0 end) as CountC
from SurveyTable
group by id
order by id;
这是一个测试数据有限的SQL Fiddle。
附录。卡洛斯发布了一个更新的结构,导致以下答案。希望这些很接近:)
这将为您提供一排非常宽的总计:
select
sum(case when Q1 = 'A' then 1 else 0 end) as Q1CountA,
sum(case when Q1 = 'B' then 1 else 0 end) as Q1CountB,
sum(case when Q1 = 'C' then 1 else 0 end) as Q1CountC,
sum(case when Q2 = 'A' then 1 else 0 end) as Q2CountA,
sum(case when Q2 = 'B' then 1 else 0 end) as Q2CountB,
sum(case when Q2 = 'C' then 1 else 0 end) as Q2CountC,
sum(case when Q3 = 'A' then 1 else 0 end) as Q3CountA,
sum(case when Q3 = 'B' then 1 else 0 end) as Q3CountB,
sum(case when Q3 = 'C' then 1 else 0 end) as Q3CountC,
sum(case when Q4 = 'A' then 1 else 0 end) as Q4CountA,
sum(case when Q4 = 'B' then 1 else 0 end) as Q4CountB,
sum(case when Q4 = 'C' then 1 else 0 end) as Q4CountC,
sum(case when Q5 = 'A' then 1 else 0 end) as Q5CountA,
sum(case when Q5 = 'B' then 1 else 0 end) as Q5CountB,
sum(case when Q5 = 'C' then 1 else 0 end) as Q5CountC
from SurveyTable;
如果您想每个问题获得一行,请尝试以下操作:
select
QuestionID,
sum(case when Answer = 'A' then 1 else 0 end) as CountA,
sum(case when Answer = 'B' then 1 else 0 end) as CountB,
sum(case when Answer = 'C' then 1 else 0 end) as CountC
from (
select 'Question1' as QuestionID, Q1 as Answer from surveytable
union all select 'Question2', Q2 from surveytable
union all select 'Question3', Q3 from surveytable
union all select 'Question4', Q4 from surveytable
union all select 'Question5', Q5 from surveytable) x
group by QuestionID
这里有一个小提琴。
另一个附录: 需要的计数ID
,并且因为ID
每行有一个,所以不需要SUM
.
这改变了方法。它首先将答案串在一起:
concat(q1,q2,q3,q4,q5) -- result for ID=1 in the test data: 'ABCAC'
A
...然后它会从字符串中吸取每一次出现:
replace(concat(q1,q2,q3,q4,q5), 'A', '') -- result for ID=1: 'BCC'
...第一个字符串 ( ABCAC
) 是长度5
,第二个字符串 ( BCC
) 是长度 3。长度的差异是A
答案的数量:2
。这差不多就是我能解释的了。现在进行查询:
select
id,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'A', '')) AS CountA,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'B', '')) AS CountB,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'C', '')) AS CountC
from surveytable;
更新的 Fiddle 在这里。
这仅提供原始数据。格式化会有点棘手,但应该不会太糟糕,特别是如果您使用前端语言进行格式化。如果您必须为此使用 MySQL,将上述内容放入子查询并在外部查询中应用格式可能会更容易:
select
id,
CONCAT('You have chosen ' ...and miles of formatting logic using CountA, etc)
from (
select
id,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'A', '')) AS CountA,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'B', '')) AS CountB,
5 - length(replace(concat(q1,q2,q3,q4,q5), 'C', '')) AS CountC
from surveytable) x