按x排序然后按SQL Server中的y列排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按x排序然后按SQL Server中的y列排序相关的知识,希望对你有一定的参考价值。
考虑像这样的表
debit credit code
-----------------------------
0 10 5
5 0 3
0 11 2
0 15 1
7 0 6
6 0 2
5 0 1
我需要生成一个这样的结果集,首先是借记,然后按代码列排序:
debit credit code
----------------------------
5 0 1
6 0 2
5 0 3
7 0 6
0 15 1
0 11 2
0 10 5
答案
你可以用它。
DECLARE @MyTable TABLE(debit INT, credit INT, code INT)
INSERT INTO @MyTable VALUES
(0, 10, 5),
(5, 0 , 3),
(0, 11, 2),
(0, 15, 1),
(7, 0 , 6),
(6, 0 , 2),
(5, 0 , 1)
SELECT * FROM
@MyTable
ORDER BY
(CASE WHEN debit > 0 THEN 0 ELSE 1 END) ,
code ,
debit
结果:
debit credit code
----------- ----------- -----------
5 0 1
6 0 2
5 0 3
7 0 6
0 15 1
0 11 2
0 10 5
另一答案
请在order by clause
中使用下面的一个,您将获得您正在寻找的输出
order by cast(cast(code as varchar(50))
+ cast(debit as varchar(2)+ cast(credit as varchar(2) as int)
另一答案
;WITH Props AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY c,cc) AS RowNumber
FROM Location
)
select * from Props order by d desc,RowNumber
试试上面的代码
另一答案
使用此选项可以帮助您:
SELECT debit, code, credit
FROM table a
WHERE debit > 0
or debit = 0
order by debit code, credit desc
要么
SELECT debit, code, credit
FROM table a
WHERE debit > 0
or debit = 0
group by debit, code, credit
order by debit code, credit desc
以上是关于按x排序然后按SQL Server中的y列排序的主要内容,如果未能解决你的问题,请参考以下文章
如何在 SQL Server 中连接字符串,并按不同的列排序/排序?
按 Sql Server 中的一列分组并按未包含在聚合函数或 GROUP BY 子句中的另一列排序