Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to calculate subtotal on column

Tags:

sql

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.

enter image description here

like image 679
Old Monk Avatar asked Mar 06 '26 15:03

Old Monk


1 Answers

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
like image 93
ScaisEdge Avatar answered Mar 09 '26 05:03

ScaisEdge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!