Oracle条件排序依据

时间:2019-02-22 19:34:53

标签: sql oracle sql-order-by

我正在尝试从数据库中获取用户及其所属部门的列表。我想按用户asc的顺序订购,首先他们没有部门,然后是其余的用户asc。下面是我当前的sql语句,该语句为我提供了用户asc列表,然后按deptCode asc排序:

SELECT
  userDepts.ID,
  users.ID AS USER_ID,                            
  userDepts.DEPT_CODE,
  users.USERNAME                                     
  FROM SCRIPTS.TB_FRSCHL_USER_DEPTS userDepts
  FULL OUTER JOIN SCRIPTS.TB_FRSCHL_USERS users ON (users.ID = userDepts.USER_ID)
  ORDER BY users.USERNAME ASC, DEPT_CODE ASC

下面是我的结果示例:

ID   | USER_ID | DEPT_CODE | USERNAME
null |   1234  |    null   |      adam.doe
null |   2341  |    null   |      ana.jane
9876 |   3412  |    cpsc   |      john.doe
4567 |   4987  |    crim   |      mike.smith
null |   4123  |    null   |      test.user

我希望它看起来像这样:

 ID   | USER_ID | DEPT_CODE | USERNAME
null |   1234  |    null   |      adam.doe
null |   2341  |    null   |      ana.jane
null |   4123  |    null   |      test.user
9876 |   3412  |    cpsc   |      john.doe
4567 |   4987  |    crim   |      mike.smith

我尝试按顺序使用CASE,但到目前为止我还没有运气。我想用sql做些什么吗?

1 个答案:

答案 0 :(得分:2)

尝试如下

SELECT
  userDepts.ID,
  users.ID AS USER_ID,                            
  userDepts.DEPT_CODE,
  users.USERNAME                                     
  FROM SCRIPTS.TB_FRSCHL_USER_DEPTS userDepts
  FULL OUTER JOIN SCRIPTS.TB_FRSCHL_USERS users ON (users.ID = userDepts.USER_ID)
  ORDER BY case when userDepts.ID is null then 1 else 2 end , users.ID