如何获得所有最大列值的总和

时间:2019-04-19 01:18:22

标签: mysql laravel

我遇到一个问题,请在下面指出。

这是表格查询

-------------------------------------------
id    title    cate    query_id    point   |
-------------------------------------------
1     A        1       1           1       |
2     B        1       1           3       |
3     C        1       1           2       |
4     A        2       2           3       |
5     B        2       2           2       |
6     C        1       2           1       |
--------------------------------------------

如果我进行分组(分类,查询)并获得最高分

----------------------------
cate    query_id    point   |
----------------------------
1       1           3       |
2       2           3       |
1       2           1       |
----------------------------

但是我想通过这样的分类来获得最大点数的总和:

--------------
cate    point |
--------------
1         4   | 
2         3   |
--------------

我希望你能帮助我。

3 个答案:

答案 0 :(得分:0)

您可以使用如下所示的派生表子查询来生成汇总:

SELECT cate, SUM(point) AS point
FROM (
    SELECT cate, query_id, MAX(point) AS point
    FROM MyTable
    GROUP BY cate, query_id
) AS t
GROUP BY cate;

答案 1 :(得分:0)

通过此操作您可以获得预期的结果

query::groupBy(cate,query_id)->sum(point)

答案 2 :(得分:0)

首先,您需要使用分组依据(类别,查询)并获取cate,query_id,max(point)

SELECT cate, query_id, MAX(point) AS point
FROM demo
GROUP BY cate, query_id

demo on dbFiddle

现在,您想从上述查询输出中通过分类获取点组总和

SELECT p.cate, SUM(p.point) AS point
FROM (
    SELECT cate, query_id, MAX(point) AS point
    FROM demo
    GROUP BY cate, query_id
) AS p
GROUP BY cate;

demo on dbfiddle