I would like to perform an operation that aggregates the values of one column based on combination of values in two other columns irrespective of which column they show up in. For example, given this table:
a b 10.0 <-
b c 5.0
c d 1.0
b a 20.0 <-
I would like to return the following (if the aggregation I want to do is a sum):
a b 30.0 <-
b c 5.0
c d 1.0
2
Answers
I’d suggest looking into the grouping and ordering functions, this is an example of how you can use group by and order by to achieve what you are trying to do –
GROUP BY
clause groups the rows by the unique combination ofcol1
andcol2
,ORDER BY
clause sorts the result in a specified order andCASE
statements to ensure that the values in columns A and B are ordered consistently so that ‘a b’ and ‘b a’ are treated as the same combination and finally,SUM
function to aggregate the values in column CWe can use
LEAST
andGREATEST
in both column selection andGROUP BY
clause:Try out on this sample fiddle based on your data.
There is no need for
CASE WHEN
here.