写一个查询来显示Id,Name和Department of No.

时间:2018-06-12 10:19:14

标签: sql oracle

我正在尝试编写一个查询来显示给定表中的Id,Name和部门编号,这些部门指的是多个部门。

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(*),但查询错误。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

在没有看到您的查询的情况下,盲目猜测是您错误地编写了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>

答案 1 :(得分:1)

您可以将{em> window 功能与subquery

一起使用
select distinct id, name, Noofdepartment
from (select t.*, count(*) over (partition by id,name) Noofdepartment
      from table t
     ) t
where Noofdepartment > 1;

但是,您也可以使用group by子句:

select id, name, count(*) as Noofdepartment
from table t
group by id, name
having count(*) > 1;

答案 2 :(得分:1)

你使用count()是正确的。您需要按其他列进行分组,并且只计算唯一的部门,然后对having子句中的数字进行过滤。

select id, name, count(distinct department) as no_of_department
from table
group by id, name
having count(distinct department) > 1

这也可以使用如下的分析函数来完成:

select *
from (
  select id, name, count(distinct department) over (partition by id, name) as no_of_department
  from table
) t
where no_of_department > 1