SQL Developer:如何以数字方式排序并将空值替换为CHAR

时间:2018-09-27 01:31:52

标签: sql oracle

git cherry-pick

输出:

enter image description here

(基于HR数据库)^代码列出了每个部门,对每个部门的员工进行计数并按数字顺序进行订购

但是我需要用一些文本替换“ null”值,我尝试使用TO_CHAR,但是当我这样做时,我无法按数字顺序对部门进行排序,我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您想要的查询是:

SELECT COALESCE(department_id, 'Some text') AS department,
       COUNT(employee_id) AS total_employees
FROM employees 
GROUP BY department_id
ORDER BY department_id;

如果department_id是一个数字,请先将其转换为字符串:

SELECT COALESCE(TO_CHAR(department_id), 'Some text') AS department,
       COUNT(employee_id) AS total_employees
FROM employees 
GROUP BY department_id
ORDER BY department_id;

注意:

  • COALESCE()是用于替换NULL值的SQL标准函数。
  • 使用SELECT DISTINCT时几乎不需要
  • GROUP BY
  • 这假设没有部门的ID为'some text'