Mysql 展平对SQL查询的响应
我正在尝试用mysql为问答表创建一个平面表。这是我的桌子 波尔问题Mysql 展平对SQL查询的响应,mysql,sql,Mysql,Sql,我正在尝试用mysql为问答表创建一个平面表。这是我的桌子 波尔问题 PollID | Question| A | B | C | D | E | TimeStamp 花粉反应 PollReponseID | PollID | UserID | Answer 在PollAnswer表中,我得到了五个答案,分别是VARCHARA、B、C、D、E select q.Question , q.PollID , r.Answer , count(r.Answer
PollID | Question| A | B | C | D | E | TimeStamp
花粉反应
PollReponseID | PollID | UserID | Answer
在PollAnswer
表中,我得到了五个答案,分别是VARCHAR
A、B、C、D、E
select q.Question
, q.PollID
, r.Answer
, count(r.Answer)
from pollQuestions q
, pollResponse r
where q.PollID = r.PollID
group
by r.Answer
, q.Question
, q.PollID
order
by r.PollID;
我写了一个查询,按照a、B、C、D、E
对答案进行分组
select q.Question
, q.PollID
, r.Answer
, count(r.Answer)
from pollQuestions q
, pollResponse r
where q.PollID = r.PollID
group
by r.Answer
, q.Question
, q.PollID
order
by r.PollID;
我的回答如下
Question | PollID | Answer | count
alpha | 1 | A | 2
alpha | 1 | B | 3
alpha | 1 | C | 4
alpha | 1 | D | 0
alpha | 1 | E | 0
betas | 2 | A | 3
betas | 2 | B | 4
betas | 2 | C | 4
betas | 2 | D | 6
betas | 2 | E | 0
我想像这样把答案压平
Question | PollID | countA | countB | countC | countD | countE
alpha | 1 | 2 | 2 | 4 | 0 | 0
betas | 2 | 3 | 4 | 4 | 6 | 0
我是否可以在不改变表结构的情况下实现这一点
任何指示都将不胜感激 您可以尝试使用条件聚合函数
select
pollQuestions.Question,
pollQuestions.PollID,
count(CASE WHEN pollResponse.Answer ='A' THEN 1 END) countA,
count(CASE WHEN pollResponse.Answer ='B' THEN 1 END) countB,
count(CASE WHEN pollResponse.Answer ='C' THEN 1 END) countC,
count(CASE WHEN pollResponse.Answer ='D' THEN 1 END) countD,
count(CASE WHEN pollResponse.Answer ='E' THEN 1 END) countE
from pollQuestions
JOIN pollResponse on pollQuestions.PollID = pollResponse.PollID
group by
pollQuestions.Question,
pollQuestions.PollID
order by
pollResponse.PollID;
注意
我会使用
JOIN
而不是逗号,
,因为JOIN
语法比更清晰,
关于连接两个表。您可以使用分组依据和求和(当…)时的情况,如下所示:
select pq.Question, pq.PollID,
sum(case when pr.Answer = 'A' then 1 else 0 end) as 'countA',
sum(case when pr.Answer = 'B' then 1 else 0 end) as 'countB',
sum(case when pr.Answer = 'C' then 1 else 0 end) as 'countC',
sum(case when pr.Answer = 'D' then 1 else 0 end) as 'countD',
sum(case when pr.Answer = 'E' then 1 else 0 end) as 'countE'
from PollQuestion pq
left join PollResponse pr on pq.PollID = pr.PollID
group by pq.Question, pq.PollID
考虑应用程序代码中的数据显示问题