首页 > 解决方案 > 编写查询以显示部门的 ID、名称和编号?

问题描述

我正在尝试编写一个查询来显示给定表中的部门 ID、名称和编号,这些表引用了多个部门。

ID      Name     Department
--      ----     ----------
1       Sam      HR
1       Sam      FINANCE
2       Ron      PAYROLL
3       Kia      HR
3       Kia      IT

结果 :

ID      Name     Department
--      ----     ----------
1       Sam               2
3       Kia               2

我尝试使用group by id和使用count(*),但查询给出错误。

我怎样才能做到这一点?

标签: sqloracle

解决方案


在没有看到您的查询的情况下,盲目的猜测是您错误地编写了该GROUP BY子句(如果您使用了它)并且忘记了包含该HAVING子句。

无论如何,这样的东西可能是你正在寻找的东西:

SQL> with test (id, name, department) as
  2    (select 1, 'sam', 'hr'      from dual union
  3     select 1, 'sam', 'finance' from dual union
  4     select 2, 'ron', 'payroll' from dual union
  5     select 3, 'kia', 'hr'      from dual union
  6     select 3, 'kia', 'it'      from dual
  7    )
  8  select id, name, count(*)
  9  from test
 10  group by id, name
 11  having count(*) > 1
 12  order by id;

        ID NAM   COUNT(*)
---------- --- ----------
         1 sam          2
         3 kia          2

SQL>

推荐阅读