查询以检索总和大于其余列的前2列

时间:2015-08-01 19:01:53

标签: mysql sql

我有一个包含5行a,b,c,d,e的表,我需要选择总和最大的前2行。

a b c d e 
1 3 4 5 6
8 6 7 8 9
5 4 9 0 1

所以我需要得到像

c  e
20 16 

所以我尝试了

select top 2* sum(a),sum(b),sum(c),sum(d),sum(e) from tablename;

2 个答案:

答案 0 :(得分:1)

您可以使用union检索具有2个最高总和的列

select colName, colSum from (
    select 'a' colName, sum(a) colSum from mytable
    union all select 'b' colName, sum(b) colSum from mytable
    union all select 'c' colName, sum(c) colSum from mytable
    union all select 'd' colName, sum(d) colSum from mytable
    union all select 'e' colName, sum(e) colSum from mytable
) t1 order by colSum desc limit 2

但是,这会将值返回为两行,而不是像示例中那样返回一行

colName, colSum
c, 20
e, 16

答案 1 :(得分:0)

考虑按如下方式重构数据:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,x CHAR(1) NOT NULL
,n INT NOT NULL
);

INSERT INTO my_table (x,n) VALUES
('a',1), 
('a',8), 
('a',5), 
('b',3), 
('b',6), 
('b',4), 
('c',4), 
('c',7), 
('c',9), 
('d',5), 
('d',8), 
('d',0), 
('e',6), 
('e',9), 
('e',1);

SELECT * FROM my_table;
+----+---+---+
| id | x | n |
+----+---+---+
|  1 | a | 1 |
|  2 | a | 8 |
|  3 | a | 5 |
|  4 | b | 3 |
|  5 | b | 6 |
|  6 | b | 4 |
|  7 | c | 4 |
|  8 | c | 7 |
|  9 | c | 9 |
| 10 | d | 5 |
| 11 | d | 8 |
| 12 | d | 0 |
| 13 | e | 6 |
| 14 | e | 9 |
| 15 | e | 1 |
+----+---+---+

然后问题变得微不足道......

SELECT x
     , SUM(n) total_n 
  FROM my_table 
 GROUP 
    BY x 
 ORDER 
    BY total_n DESC 
 LIMIT 2;
+---+---------+
| x | total_n |
+---+---------+
| c |      20 |
| e |      16 |
+---+---------+