alpha 列的条件 SQL ORDER BY ASC/DESC

2023-10-26数据库问题
2

本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12