Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to sort columns within each row and order rows based on this

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
like image 820
slashmais Avatar asked Dec 12 '25 05:12

slashmais


1 Answers

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
  • see it working in an sqlfiddle
  • see here for min() and max() functions

Quote:

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.

like image 100
fancyPants Avatar answered Dec 13 '25 21:12

fancyPants