我有一个mysql查询如下:
SELECT questionid, question_number, question, actual_score, total_score,
ROUND(((actual_score / total_score) * 100), 2) AS satisfaction FROM
(
SELECT seq.`questionid`, seq.`question_number`, seql.`question`,
SUM(sea.`score`) AS actual_score,
SUM(seq.`max_score`) AS total_score
-- round(((sea.`score` / seq.`max_score`) * 100), 2) as satisfaction
FROM `survey_event_questions` seq
INNER JOIN `survey_event_question_langs` seql ON seq.`questionid` = seql.`questionid` AND seql.`langid` = '1'
INNER JOIN `survey_event_answers` sea ON seq.`questionid` = sea.`questionid`
INNER JOIN `survey_events` se ON sea.`eventid` = se.`eventid`
WHERE seq.`event_typeid` = '1' AND seq.`max_score` > 0 AND se.`survey_date` BETWEEN
'2014-01-02 13:00:00' AND '2014-05-02 14:59:59' AND se.`event_status` = 'Closed'
GROUP BY seq.`questionid`
) AS tbl;
此查询总结了sea.score和seq.max_score的列值,并正确计算了满意度值。
我想在不使用嵌套查询的情况下执行此操作。我正在使用的单个查询如下。
SELECT seq.`questionid`, seq.`question_number`, seql.`question`,
SUM(sea.`score`) AS actual_score,
SUM(seq.`max_score`) AS total_score,
round(((sea.`score` / seq.`max_score`) * 100), 2) as satisfaction
FROM `survey_event_questions` seq
INNER JOIN `survey_event_question_langs` seql ON seq.`questionid` = seql.`questionid` AND seql.`langid` = '1'
INNER JOIN `survey_event_answers` sea ON seq.`questionid` = sea.`questionid`
INNER JOIN `survey_events` se ON sea.`eventid` = se.`eventid`
WHERE seq.`event_typeid` = '1' AND seq.`max_score` > 0 AND se.`survey_date` BETWEEN
'2014-01-02 13:00:00' AND '2014-05-02 14:59:59' AND se.`event_status` = 'Closed'
GROUP BY seq.`questionid`
当我运行此查询时,它给出了满意列的错误计算,但在使用嵌套查询时工作正常。
答案 0 :(得分:1)
使用以下查询
SELECT seq.`questionid`, seq.`question_number`, seql.`question`,
SUM(sea.`score`) AS actual_score,
SUM(seq.`max_score`) AS total_score,
round(((SUM(sea.`score`) / SUM(seq.`max_score`)) * 100), 2) as satisfaction
FROM `survey_event_questions` seq
INNER JOIN `survey_event_question_langs` seql
ON seq.`questionid` = seql.`questionid`
AND seql.`langid` = '1'
INNER JOIN `survey_event_answers` sea ON seq.`questionid` = sea.`questionid`
INNER JOIN `survey_events` se ON sea.`eventid` = se.`eventid`
WHERE seq.`event_typeid` = '1' AND seq.`max_score` > 0
AND se.`survey_date` BETWEEN
'2014-01-02 13:00:00' AND '2014-05-02 14:59:59' AND se.`event_status` = 'Closed'
GROUP BY seq.`questionid`