What SQL select query can I use to sort each row and then order the sorted rows?
E.g.: table tab (c1, c2, c3, c4)
2,5,8,4
2,1,6,7
5,2,9,3
The query must give:
1,2,6,7
2,3,5,9
2,4,5,8
SELECT
MIN(c1, c2, c3, c4) AS new_c1,
CASE MIN(c1, c2, c3, c4) WHEN c1 THEN MIN(c2, c3, c4)
WHEN c2 THEN MIN(c1, c3, c4)
WHEN c3 THEN MIN(c1, c2, c4)
WHEN c4 THEN MIN(c1, c2, c3)
END AS new_c2,
CASE MAX(c1, c2, c3, c4) WHEN c1 THEN MAX(c2, c3, c4)
WHEN c2 THEN MAX(c1, c3, c4)
WHEN c3 THEN MAX(c1, c2, c4)
WHEN c4 THEN MAX(c1, c2, c3)
END AS new_c3,
MAX(c1, c2, c3, c4) AS new_c4
FROM tab
ORDER BY new_c1, new_c2, new_c3, new_c4
min() and max() functionsQuote:
Note that max() [and min()] is a simple function when it has 2 or more arguments but operates as an aggregate function if given only a single argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With