Conditional SQL ORDER BY ASC/DESC for alpha columns(alpha 列的条件 SQL ORDER BY ASC/DESC)
问题描述
在 MS SQL Server 2008 R2 中编写存储过程,我想避免使用 DSQL...
Writing a stored procedure in MS SQL Server 2008 R2, I want to avoid using DSQL...
我希望排序方法(ASC 或 DESC)是有条件的.
I would like the sort method (ASC or DESC) to be conditional.
现在,对于数字列,我将简单地使用 case 语句并否定该值以模拟 ASC 或 DESC...即:
Now, with a numeric column I would simply use a case statement and negate the value to emulate ASC or DESC... That is:
... ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [NumericColumn] ELSE -[NumericColumn] END ASC
使用 alpha 列执行此操作的合适方法是什么?
What is an appropriate method for doing this with an alpha column?
我想到了一个聪明的方法,但它似乎非常低效......我可以将我的有序 alpha 列插入一个带有自动编号的临时表中,然后使用上述方法按自动编号排序.
I thought of a clever way but it seems terribly inefficient... I could insert my ordered alpha column into a temp table with an autonumber then sort by the autonumber using the method described above.
编辑 2:
你们如何看待这种方法?
What do you guys think of this approach?
ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [AlphaColumn] ELSE '' END ASC,
CASE @OrderAscOrDesc WHEN 0 THEN '' ELSE [AlphaColumn] END DESC
我不知道强制对统一列进行排序是否比从排序字符串中导出数字更有效
I don't know if forcing a sort on a uniform column is more efficient than deriving numbers from sorted strings though
推荐答案
一个选项
;WITH cQuery AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY SortColumn) AS RowNum
FROM
MyTable
)
SELECT
*
FROM
cQuery
ORDER BY
RowNum * @Direction --1 = ASC or -1 = DESC
或者恕我直言有点丑的案例
Or CASE which IMHO is a bit uglier
ORDER BY
CASE WHEN 'ASC' THEN SortColumn ELSE '' END ASC,
CASE WHEN 'DESC' THEN SortColumn ELSE '' END DESC
这篇关于alpha 列的条件 SQL ORDER BY ASC/DESC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:alpha 列的条件 SQL ORDER BY ASC/DESC
基础教程推荐
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01