SQL 对每行中的列进行排序,并据此对行进行排序

标签 sql sqlite sorting select

我可以使用什么 SQL 选择查询对每一行进行排序,然后对排序后的行进行排序?

例如:表格选项卡(c1、c2、c3、c4)

2,5,8,4
2,1,6,7
5,2,9,3

查询必须给出:

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
  • 看到它在 sqlfiddle 中工作
  • 参见here对于 min()max() 函数

引用:

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.

关于SQL 对每行中的列进行排序,并据此对行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18719310/

相关文章:

.net - 事务应该在存储过程外部还是内部指定?

sql - Sequelize findOrCreate 插入新行但返回主键 undefined object

mysql - 如何纠正这个 ('Cannot delete or update a parent row' )?

sql - Oracle SQL 获取括号中的最后一个字符串(也可能包含括号)

Android SQLite 从外部存储文件夹读取数据库

jquery - 如何在 <span> 中按内容日期对 div 进行排序

activerecord - 如何使用 Active Record 在 Sinatra 中静音 SQLite3 记录器?

SQLite 整数大小 : individually sized or for the entire group

c++ - 如何 list.sort(member Function);?

python - 在python中对字典列表的列表进行排序