请注意我在代码
下面做了一个SELECT我创建了一个SQL小提琴,因此您不必在本地数据库中重新创建此示例。 http://sqlfiddle.com/#!9/4c657
问题基本上不是将费率作为数字来获取,而应将其作为百分比,例如:
糟糕:25%,好10%,非常好:30%:优秀:45%
目前我只是在显示数字,我不确定是否应该使用SELECT FROM(SELECT ...)和GROUP BY,或者是否有更好的方法。由于我对此有疑问,我想提出一些建议。谢谢!
由于
/*What I've got so far*/
SELECT qg.name AS questionGroup,q.name AS question,(rate=1) AS bad ,(rate=2) AS regular,(rate=3) AS good, (rate=4) AS veryGood, (rate=5) AS excellent from answers AS a INNER JOIN questions AS q ON q.id=a.questionId INNER JOIN questionGroups as qg ON qg.id = q.groupId;
CREATE TABLE `guidedVisits` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `questionGroups` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `questions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`groupId` int(10) unsigned NOT NULL,
`name` varchar(120) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_groupId` (`groupId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `answers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`visitId` int(10) unsigned NOT NULL,
`questionId` int(10) unsigned NOT NULL,
`rate` tinyint(4) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_questionId` (`questionId`),
KEY `idx_visitId` (`visitId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
INSERT INTO `questionGroups` VALUES (1,'About us'),(2,'Facility');
INSERT INTO `questions` VALUES (1,1,'Did you like us?'),(2,1,'What do you think about our ads?'),(3,2,'Were our reception chairs comfortable?'),(4,2,'Was everything clean as you would expect?');
INSERT INTO `guidedVisits` VALUES (1,'2015-03-31'),(2,'2015-03-31');
INSERT INTO `answers` VALUES (1,1,1,3),(2,1,2,4),(3,1,3,4),(4,1,4,5),(5,1,1,5),(6,1,2,5),(7,1,3,5),(8,1,4,5);
答案 0 :(得分:1)
SELECT qg.name AS questionGroup,q.name AS question, CASE WHEN AVG(rate) < 25 THEN 'bad' WHEN AVG(rate) < 35 THEN 'good' .. END AS rateDesc
FROM answers AS a INNER JOIN questions AS q
ON q.id=a.questionId INNER JOIN questionGroups as qg
ON qg.id = q.groupId
GROUP BY qg.name,q.name
答案 1 :(得分:0)
SELECT r.questionGroup,r.question,r.qid,
FLOOR(AVG(r.bad)*100) AS bad, FLOOR(AVG(r.regular)*100) AS regular,
FLOOR(AVG(r.good)*100) AS good, FLOOR(AVG(r.veryGood)*100) AS veryGood,
FLOOR(AVG(r.excellent)*100) AS excellent
FROM (
SELECT q.id AS qid,qg.id AS gid,
qg.name AS questionGroup,q.name AS question,
(rate=1) AS bad ,(rate=2) AS regular,
(rate=3) AS good, (rate=4) AS veryGood,
(rate=5) AS excellent FROM answers AS a
INNER JOIN questions AS q ON q.id=a.questionId
INNER JOIN questionGroups as qg ON qg.id = q.groupId
WHERE visitId=1) AS r GROUP BY r.qid;