mysql按SUM(column)组排序,另一列

时间:2018-09-03 14:44:48

标签: mysql

我有以下数据库表:

create table table1 (
col1 VARCHAR(5) NOT NULL,
col2 VARCHAR(5) NOT NULL,
col3 TINYINT NOT NULL,
col4 INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);

INSERT INTO table1 VALUES
('b','c',1,NULL),
('b','d',2,NULL),
('a','e',1,NULL),
('a','f',3,NULL); 

mysql> select * from table1;
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| b    | c    |    1 |    1 |
| b    | d    |    2 |    2 |
| a    | e    |    1 |    3 |
| a    | f    |    3 |    4 |
+------+------+------+------+
4 rows in set (0.00 sec)

我想创建一个查询,该查询按col1上的SUM(col3)GROUP排序行。 然后我需要订购col3 DESC。

So final table will look like:
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| a    | f    |    3 |    4 |
| a    | e    |    1 |    3 |
| b    | d    |    2 |    2 |
| b    | c    |    1 |    1 |
+------+------+------+------+

i can get the SUM(col1):
mysql> select sum(col3) from table1 group by col1;
+-----------+
| sum(col3) |
+-----------+
|         4 |
|         3 |
+-----------+

,但不确定如何继续。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

一种选择是加入一个子查询,以求和:

SELECT t1.*
FROM table1 t1
INNER JOIN
(
    SELECT col1, SUM(col3) AS col3_sum
    FROM table1
    GROUP BY col1
) t2
    ON t1.col1 = t2.col1
ORDER BY
    t2.col3_sum DESC,
    t1.col1,
    t1.col3 DESC;

如果您使用的是MySQL 8+或更高版本,那么我们可以在SUM子句中尝试使用ORDER BY作为分析函数:

SELECT *
FROM table1
ORDER BY
    SUM(col3) OVER (PARTITION BY col1) DESC,
    col1,
    col3 DESC;

enter image description here

Demo

答案 1 :(得分:0)

这是我想出的:

select table1.* 
from table1
join (
    select col1,sum(col3) as col5
    from table1
    group by col1
     ) t2
on table1.col1=t2.col1
order by col5 desc, col3 desc;

但是我认为@ tim-beigeleisen首先到达那里:)