8

我有以下表格元素我如何运行一个重现表格的查询,但在底部有一个额外的行显示 col2 的总和

Col1  | col2  
---------------
Water |  22  
water |   3      
water |   5      
Air   |  10      
Earth |   3       
Air   |   5    
4

3 回答 3

12

我不知道你为什么想要那个,但试试这个:

SELECT Col1, Col2 FROM tableName
UNION
SELECT 'SUM' as Col1, SUM(Col2) Col2 FROM tableName
于 2012-04-06T01:37:06.623 回答
4
insert into table_name(col2) (select sum(col2) from table_name) as a

告诉我这是否有效。

于 2012-04-06T04:44:38.887 回答
3
select IFNULL(col1,'SUM') col1,sumcol2 col2
from (select col1,col2,sum(col2) sumcol2
from summation_trick
group by col1,col2
with rollup) B
where (col1 is null and col2 is null)
or (col1 is not null and col2 is not null);

这是您加载的数据

mysql> use junk
Database changed
mysql> drop table if exists summation_trick;
Query OK, 0 rows affected (0.04 sec)

mysql> create table summation_trick
    -> (
    ->     col1 varchar(20),
    ->     col2 int
    -> );
Query OK, 0 rows affected (0.09 sec)

mysql> insert into summation_trick values
    -> ('Water',22  ),('water', 3  ),
    -> ('water', 5  ),('Air'  ,10  ),
    -> ('Earth', 3  ),('Air'  , 5  );
Query OK, 6 rows affected (0.05 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql>

这是执行的查询

mysql> select IFNULL(col1,'SUM') col1,sumcol2
    -> from (select col1,col2,sum(col2) sumcol2
    -> from summation_trick
    -> group by col1,col2
    -> with rollup) B
    -> where (col1 is null and col2 is null)
    -> or (col1 is not null and col2 is not null);
+-------+---------+
| col1  | sumcol2 |
+-------+---------+
| Air   |       5 |
| Air   |      10 |
| Earth |       3 |
| water |       3 |
| water |       5 |
| Water |      22 |
| SUM   |      48 |
+-------+---------+
7 rows in set (0.00 sec)

mysql>
于 2012-04-06T05:00:46.497 回答