简体   繁体   中英

SQL query to calculate subtotal on column

I have a table which have two column say Column1 and Column2. Column1 comprises of Key and Column2 comprises of Values.

I have to display all key-value pair along with key-group sum.

Currently I am ordering the values by Column1 and calculating sum for each key in view using a local variable.

Can this be merged in a single SQL query.

Please see below image for further diagrammatic view.

在此输入图像描述

Yiou can use union all ordered

 select column1  , column2
 from my_table 
 union all  
 select concat(column1, ' - Sub Total') as column1, sum(column2) 
 from my_table 
 group by column1
 order by column1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM