由另一列分组的SUM(列)的mysql顺序

问题描述 投票:1回答:2

我有以下数据库表:

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'd对行进行排序。然后我需要ORDER 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 |
+-----------+

但不知道如何继续。任何帮助赞赏。

mysql
2个回答
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


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首先到达那里:)

© www.soinside.com 2019 - 2024. All rights reserved.