按多列但不同的条件排序

Sort by multiple columns but different crietria

我在 SQL 服务器中有一个 table,我想从中 select 使用 order by 的记录,但我有不同的情况。请看下面table.

EmployeeCode | EmployeeArea
    001      |     8568
    002      |     4549
    004      |     4549
    005      |     8568
    003      |     4549
    006      |     7777
    010      |     4549
    007      |     8568
    008      |     7777
    009      |     4549

如上所示,我有两个字段Employee Code和Employee Area。现在,我想要做的是先按员工代码对记录进行排序,然后再按员工区域对记录进行排序,但不是以标准方式。请参阅下面所需的 o/p 以便更好地理解

  EmployeeCode   | EmployeeArea
        001      |     8568
        005      |     8568
        007      |     8568
        002      |     4549
        003      |     4549
        004      |     4549
        009      |     4549
        010      |     4549
        006      |     7777
        008      |     7777

如上图第一个排序是在employeeCode上,根据第一个employee(ex 001)的Employee Area(8568)所有areacode为01的员工放在一起,按照employee code升序排列. 我厌倦了使用 group by、CTE、临时 tables 等多种方式,但无法获得所需的输出。任何帮助将不胜感激。

如果我理解你的话,你只需要按两列排序:

SELECT EmplyeeCode, EmplyeeArea
FROM yourTable
ORDER BY EmplyeeArea, EmplyeeCode

此处我在 DB<>FIDDLE 上创建了演示。输出如你所愿。

看来您需要的是 ORDER BY 中的窗口 MIN:

SELECT *
FROM (VALUES('001',8568),
            ('002',4549),
            ('004',4549),
            ('005',8568),
            ('003',4549),
            ('006',7777),
            ('010',4549),
            ('007',8568),
            ('008',7777),
            ('009',4549))V(EmployeeCode,EmployeeArea)
ORDER BY MIN(EmployeeCode) OVER (PARTITION BY EmployeeArea),
         EmployeeCode,
         EmployeeArea;