通过SQL中的另一列对具有重复值的列进行排序

use*_*808 2 sql database sql-server

我有一张桌子:

+------+--------+
| Type |Location|
+------+--------+
| 0003 |   US   |
| 0010 |   US   |
| 0007 |   CA   |
| 0013 |   MX   |
| 0003 |   EU   |
| 0007 |   MX   |
| 0219 |   CN   |
+------+--------+
Run Code Online (Sandbox Code Playgroud)

我需要按“位置”对它进行排序,除非在“类型”列中找到重复项。然后,在继续按“位置”进行排序之前,下一行应重复(或更多重复)。

预期结果:

+------+--------+
| Type |Location|
+------+--------+
| 0007 |   CA   |
| 0007 |   MX   | <---- Exception (duplicate of 0007)
| 0219 |   CN   |
| 0003 |   EU   |
| 0003 |   US   | <---- Exception (duplicate of 0003)
| 0013 |   MX   |
| 0010 |   US   |
+------+--------+
Run Code Online (Sandbox Code Playgroud)

我尝试过使用cte和row_number,但是我无法靠近任何地方。我不确定这是否是一个好方法,但是我无法想到任何其他解决方案。

Gor*_*off 5

您可以在窗口中使用窗口函数来执行所需的操作order by

select t.*
from t
order by (min(location) over (partition by type)),
         location
Run Code Online (Sandbox Code Playgroud)