简体   繁体   English

如何在SQL Server 2008 R2中对多列进行排序?

[英]How to sort multiple columns in SQL Server 2008 R2?

There is a plain sort with order by clause with multiple columns separated by commas. 有一个由order by子句进行的普通排序,其中多个列用逗号分隔。 But I am not looking for that. 但是我不是在寻找那个。 Please read below 请在下面阅读

The returned default result set is sorted by sequence column. 返回的默认结果集按序列列排序。 Note sequence 46 and 47 which are in order with different ReqTag and Rank. 注意序列46和47,它们具有不同的ReqTag和Rank。 I am trying to keep the ReqTag column together but sorted by sequence and Rank. 我试图将ReqTag列保持在一起,但按顺序和等级排序。

sequence | Reqtag | Rank
-------- | ------ | -------
42       | PD     | 1
43       | PD     | 2
46       | MQ     | 1
46       | SD     | 3
47       | MQ     | 2
47       | SD     | 4
48       | MO     | 1

Now, I want the display to be like below where sequence and rank column are used (desired result set) 现在,我希望显示如下所示,其中使用了sequence和rank列(所需的结果集)

sequence | Reqtag | Rank
-------- | ------ | ------
42       | PD     | 1
43       | PD     | 2
46       | MQ     | 1
47       | MQ     | 2
46       | SD     | 3
47       | SD     | 4
48       | MO     | 1

Any ideas are appreciated. 任何想法表示赞赏。 Thank you for your time. 感谢您的时间。

You can use window functions in the sort. 您可以在排序中使用窗口函数。 I think you want: 我想你要:

order by min(sequence) over (partition by reqtag),
         min(rank) over (partition by reqtag),
         rank

If the order of the ReqTag is not important other than that they are grouped together then you should be able to change your sort to be the following: 如果ReqTag的顺序除了将它们组合在一起之外并不重要,那么您应该可以将排序更改为以下内容:

SELECT sequence, ReqTag, Rank
FROM [Table]
ORDER BY ReqTag, sequence, Rank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM