Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: partition over two columns

I have following table:

---------------------
| No1 | No2  | Amount
---------------------
| A   |  B   |    10 |
| C   |  D   |    20 |
| B   |  A   |    30 |
| D   |  C   |    40 |
---------------------

and I want to sum over partition by both columns (No1,No2) but it should group also when the values are changed in the two columns. Example would be: AB = BA

This would be my expected result:

-----------------------------------------
| No1 | No2  | Sum(Amount) over partition
-----------------------------------------
| A   |  B   |    40                    |
| C   |  D   |    60                    |
| B   |  A   |    40                    |
| D   |  C   |    60                    |
-----------------------------------------

Any ideas?

like image 950
ZerOne Avatar asked Nov 25 '25 09:11

ZerOne


1 Answers

Use least and greatest.

select no1,no2,sum(amount) over(partition by least(no1,no2),greatest(no1,no2)) as total
from tbl
like image 102
Vamsi Prabhala Avatar answered Nov 26 '25 22:11

Vamsi Prabhala



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!