查找聚合的最高值并存储在新列中

时间:2017-08-23 11:34:11

标签: mysql

我有一个查询来总结一些表的答案,现在想找出哪一个答案最多。这是我的问题:

SELECT Sum(surveys_answers.answer) AS Commitments
FROM   surveys 
       LEFT JOIN surveys_answers 
              ON surveys_answers.surveys_id_fk = surveys.surveys_id 
       LEFT JOIN surveys_times 
              ON surveys_answers.answer_time_id = surveys_times.times_id 
WHERE  surveys.surveys_id = 5132 
       AND surveys_answers.answer = 1 
GROUP  BY times_id 
ORDER  BY times_id 

由于我只需要承诺数量,因此这是我唯一选择的专栏。但我还需要确定哪一行承诺最多,并且想要添加一个新列"最高"类型为boolean,对于具有最高值的行包含true。

我尝试使用Max(承诺)AS最高,但它不起作用。这可以在不创建子查询的情况下实现吗?

目前我得到以下结果:

+-------------+
| Commitments |
+-------------+
| 4           |
+-------------+
| 7           |
+-------------+
| 2           |
+-------------+
| 13          |
+-------------+
| 8           |
+-------------+

我想要一个这样的结果:

+-------------+---------+
| Commitments | Highest |
+-------------+---------+
| 4           | false   |
+-------------+---------+
| 7           | false   |
+-------------+---------+
| 2           | false   |
+-------------+---------+
| 13          | true    |
+-------------+---------+
| 8           | false   |
+-------------+---------+

提前致谢! :)

1 个答案:

答案 0 :(得分:1)

您可以在此处使用会话变量技巧。定义行号会话变量,当它等于1时,它是最高的,否则不是:

SET @rn = 0;

SELECT
    t.Commitments,
    CASE WHEN rn = 1 THEN 'true' ELSE 'false' END AS Highest
FROM
(
    SELECT
        t.times_id,
        t.Commitments,
        @rn:=@rn+1 AS rn
    FROM
    (
        SELECT
            times_id,
            SUM(surveys_answers.answer) AS Commitments
        FROM surveys
        LEFT JOIN surveys_answers 
            ON surveys_answers.surveys_id_fk = surveys.surveys_id 
        LEFT JOIN surveys_times 
            ON surveys_answers.answer_time_id = surveys_times.times_id 
        WHERE
            surveys.surveys_id = 5132 AND
            surveys_answers.answer = 1 
        GROUP BY times_id 
    ) t
    ORDER BY t.Commitments DESC
) t
ORDER BY t.times_id