Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing Values From Calculated Column From Distinct Rows

I have data in the following format.

Column 1 and Value from the database. I use a LEFT() function to extract Column 2. Where I need help is to sum the values from the newly calculated Column 2 and list the sums a new column.

https://i.sstatic.net/WNgkU.png

Any help is appreciated. Thanks.

like image 388
Nich Avatar asked Apr 28 '26 07:04

Nich


2 Answers

Basically, you seem to want an aggregation with a function for the aggregation key:

select left(column1, 1), sum(value)
from t
group by left(column1, 1);
like image 135
Gordon Linoff Avatar answered Apr 30 '26 20:04

Gordon Linoff


SELECT *
    ,CalculatedColumn2 = LEFT(Column1,1)
    ,Value
    ,CalculatedSum = SUM(Value) OVER (PARTITION BY LEFT(Column1,1))
FROM
    Table

While Gordon's answer get's you the SUM if you want it per row you can use a partitioned window Function such as SUM() OVER.

like image 27
Matt Avatar answered Apr 30 '26 21:04

Matt



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!