简体   繁体   中英

How to order by column 1 equal column 2 in SQL

I have a set of columns for which I would like to order by set of 2 rows. For example as follow:

col1  col2

1     4
2     5
3     6
4     1
5     2
6     3

Desired output:

col1  col2

1     4
4     1
2     5
5     2
3     6
6     3

Any help would be appreciated.

You must sort by the smallest of the columns first and the largest next:

ORDER BY CASE WHEN col1 < col2 THEN col1 ELSE col2 END,
         CASE WHEN col1 < col2 THEN col2 ELSE col1 END

Most databases support functions like MySql's LEAST() and GREATEST() which simplify the code:

ORDER BY LEAST(col1, col2),
         GREATEST(col1, col2)

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.

Sort by multiple column : ORDER BY column1 DESC, column2
SELECT * FROM table_name ORDER BY col1 ASC;             -- ASCending is default
SELECT * FROM table_name ORDER BY col1 DESC;            -- DESCending
SELECT * FROM table_name ORDER BY col1 DESC, col2;      -- col1 DESC then col2 ASC


I think your SQL sentence must contain next ORDER BY clause:

ORDER BY col1 + col 2 ASC, col1 ASC 

will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM