【发布时间】:2010-10-20 00:12:28
【问题描述】:
我想让我的查询中的排序有条件,所以如果它满足条件,它应该按降序排序
例如:
SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END
【问题讨论】:
标签: sql sql-server sql-order-by
我想让我的查询中的排序有条件,所以如果它满足条件,它应该按降序排序
例如:
SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END
【问题讨论】:
标签: sql sql-server sql-order-by
以 ASC 或 DESC 顺序动态排序,与数据类型无关。
第一个示例按字母顺序排序,第二个示例使用数字。 @direction 变量表示排序方向(0 = ASC 或 1 = DESC),[column] 是排序列。
这也适用于多列排序,如果放置在更远的外部查询中,您可以隐藏 [row] 列。
DECLARE @direction BIT = 1 -- 0 = ASC or 1 = DESC
-- Text sort.
SELECT
IIF(@direction = 0, ROW_NUMBER() OVER (ORDER BY [column] ASC), ROW_NUMBER() OVER (ORDER BY [column] DESC)) [row]
, *
FROM
( -- your dataset.
SELECT N'B' [column]
UNION SELECT N'C'
UNION SELECT N'A'
) [data] ORDER BY [row]
-- Numeric sort.
SELECT
IIF(@direction = 0, ROW_NUMBER() OVER (ORDER BY [column] ASC), ROW_NUMBER() OVER (ORDER BY [column] DESC)) [row],
*
FROM
( -- your dataset.
SELECT 2 [column]
UNION SELECT 3
UNION SELECT 1
) [data] ORDER BY [row]
【讨论】:
您还可以使用支持所有列类型的方案:
SELECT <column_list> FROM <table>
ORDER BY
CASE WHEN @sort_order = 'ASC' AND @sort_column = '<column>' THEN <column> END ASC,
CASE WHEN @sort_order = 'DESC' AND @sort_column = '<column>' THEN <column> END DESC
【讨论】:
SELECT *
FROM Data
ORDER BY
Case WHEN @Direction = 1 THEN SortOrder END DESC,
Case WHEN 1=1 THEN SortOrder END
【讨论】:
不要更改ASC或DESC,更改正在排序的事物的符号:
SELECT * FROM table
ORDER BY
CASE WHEN @Direction = 1 THEN -id else id END asc;
OP 询问:
各位,我不是SQL专家,请解释一下id和-id是什么意思,它控制排序方向吗?
id 就是您要排序的任何列; -id 只是对它的否定,id * -1。如果您按多列排序,则需要对每一列取反:
SELECT * FROM table
ORDER BY
CASE WHEN @Direction = 1 THEN -id else id END
CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ;
如果您按非数字列排序,则需要找到使该列“负数”的表达式;编写一个函数来做到这一点可能会有所帮助。
【讨论】:
我做过类似的事情
select productId, InventoryCount,
case
when @Direction = 1 then InventoryCount
else -InventoryCount
end as "SortOrder"
order by 3
【讨论】: