根据每个字段的顺序查询 returns 列表 (SQL)
Query returns list based on order by each field (SQL)
我只想在 table 中使用一个查询 (SQl),它有多个 "order by" 字段。
我希望每个字段的每个 "order by" 查询到 return 个基于 table
中的数据的单独列表结果
例如:
name c1 c2
"a" 1 2
"b" 3 4
"c" 2 1
"d" 3 1
"e" 1 4
"f" 3 4
"g" 5 2
"h" 4 4
我想通过一个查询 return 1 个基于 "c1" 和 "c2" (asc) 顺序的列表,如下所示:
"a" 1 2 --> order asc by c1
"e" 1 4
"c" 2 1
"b" 3 4
"d" 3 1
"f" 3 4
"h" 4 4
"g" 5 2
----------
"c" 2 1 ---> order asc by c2
"d" 3 1
"a" 1 2
"g" 5 2
"b" 3 4
"e" 1 4
"f" 3 4
"h" 4 4
这是你想要的吗?
select t.*
from t cross join
(values ('col1'), ('col2')) v(which)
order by v.which,
(case when which = 'col1' then col1 end) asc,
(case when which = 'col2' then col2 end) asc;
请注意,两个单独的查询可能更快,原因有二:
- 排序时间复杂度为 O(n * ln(n)),这意味着将要排序的数据加倍会使排序所需的时间增加一倍以上。
- 如果你在
col1
and/orcol2
上有索引,那么索引可以用来排序。使用更复杂的键是不可能的。
我只想在 table 中使用一个查询 (SQl),它有多个 "order by" 字段。
我希望每个字段的每个 "order by" 查询到 return 个基于 table
中的数据的单独列表结果例如:
name c1 c2
"a" 1 2
"b" 3 4
"c" 2 1
"d" 3 1
"e" 1 4
"f" 3 4
"g" 5 2
"h" 4 4
我想通过一个查询 return 1 个基于 "c1" 和 "c2" (asc) 顺序的列表,如下所示:
"a" 1 2 --> order asc by c1
"e" 1 4
"c" 2 1
"b" 3 4
"d" 3 1
"f" 3 4
"h" 4 4
"g" 5 2
----------
"c" 2 1 ---> order asc by c2
"d" 3 1
"a" 1 2
"g" 5 2
"b" 3 4
"e" 1 4
"f" 3 4
"h" 4 4
这是你想要的吗?
select t.*
from t cross join
(values ('col1'), ('col2')) v(which)
order by v.which,
(case when which = 'col1' then col1 end) asc,
(case when which = 'col2' then col2 end) asc;
请注意,两个单独的查询可能更快,原因有二:
- 排序时间复杂度为 O(n * ln(n)),这意味着将要排序的数据加倍会使排序所需的时间增加一倍以上。
- 如果你在
col1
and/orcol2
上有索引,那么索引可以用来排序。使用更复杂的键是不可能的。