SQL - 分组依据和计数

SQL - GROUP BY and COUNT

我有一个 table 列 - 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 的条目总数。

这个怎么样?

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

您可以对部门和员工进行分组,并加入您对部门进行分组以计算员工数量的查询:

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

问题的具体答案是:

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;