SQL - GROUP BY和COUNT

时间:2015-05-09 14:15:49

标签: sql oracle group-by

我有一张表--D - 和E. 我想在每个D中获得D,Distinct E,每个D的总条目数。如何为此编写SQL?

数据:

D | E
-----
1 | K
1 | K
1 | A
2 | S
2 | S
2 | S
2 | S

所需的o / p:

    D | E | Total_E_in_D
   ----------------------
    1 | K | 3
    1 | A | 3
    2 | S | 4 
    SELECT D,E,Count(E in each D) 
    FROM table
    GROUP BY D,E.

最后一列应该为我提供每个D的总条目数。

3 个答案:

答案 0 :(得分:2)

问题的具体答案是:

select dept, count(*) as numemployees, count(distinct emp) as numDistinctEmployees
from d1
group by dept;

这似乎很不寻常,因为它假设员工不止一次在同一个部门。

编辑:

奇怪的数据格式,但只使用聚合与分析函数:

select dept, emp, sum(count(*)) over (partition by dept) as numEmployees
from d1
group by dept, emp;

答案 1 :(得分:1)

您可以对部门和员工进行分组,然后加入查询,在该查询中您对部门进行分组以计算员工数量:

select
  e.Dept,
  e.Emp
  d.EmpCount
from
  table e
  inner join (
    select
      Dept,
      count(distinct Emp) as EmpCount
    from
      table
    group by
      Dept
  ) d on d.Dept = e.Dept
group by
  e.Dept, e.Emp

您还可以使用子查询来计算员工数:

select
  e.Dept,
  e.Emp,
  (
    select
      count(distinct Emp)
    from
      table d
    where
      d.Dept = e.Dept
  ) as EmpCount
from
  table e
group by
  e.Dept, e.Emp

答案 2 :(得分:-1)

这是怎么回事?

select dept, emp, (select count(*) from table t2 where t2.dept = t1.dept) noEmps
from table t1