在SQL上显示列值及其计数

时间:2018-12-24 20:11:59

标签: mysql sql

我只想问你一个关于SQL的问题。

让我们考虑一下这个EMPLOYEE表:

Employee     Department
A               10
A               10
A               11
A               12
B               13
B               13        

我要显示的是每个雇员,所有不同部门(无重复)以及这些不同部门的总数。因此,如下所示:

Employee     Department      total_dept     
A               10             3
A               11             3
A               12             3
B               13             1

如果可能的话,我甚至更喜欢这样的东西:

Employee     Department      total_dept     
A               10             3
A               11             null
A               12             null
B               13             1

我有一个很大的表(有很多列和许多数据),所以我认为这可以是一种“优化”,不是吗?我的意思是,无需在所有行中存储total_dept。只要足够就放它。没问题,如果之后我将该列留空。但是我不知道是否有可能在SQL中做这样的事情。

那么,我该如何解决?我尝试过,但似乎无法将count(column)与同一列组合在一起...

提前谢谢

3 个答案:

答案 0 :(得分:2)

这可能就是您要寻找的

SELECT
  emp,
  dept,
  (select count(distinct dept) from TB as tbi where tb.emp = tbi.emp ) x
FROM TB
group by emp, dept;

答案 1 :(得分:1)

MySQL 8.0支持窗口COUNT

SELECT *,COUNT(*) OVER (PARTITION BY Employee) AS total_dept
FROM (SELECT DISTINCT * FROM Employees) e

db<>fiddle demo


您甚至可能会有第二个结果(我建议将演示文稿留给应用层):

SELECT *, CASE WHEN ROW_NUMBER() OVER(PARTITION BY Employee ORDER BY Department) = 1
               THEN COUNT(*) OVER (PARTITION BY Employee) END AS total_dept
FROM (SELECT DISTINCT * FROM Employees) e
ORDER BY Employee, Department;

db<>fiddle demo

答案 2 :(得分:0)

对于第二版:

SELECT 
  DISTINCT e.Employee, e.Department, 
  CASE 
    WHEN e.Department = 
      (SELECT MIN(Department) FROM Employees WHERE Employees.Employee = e.Employee) 
      THEN
        (SELECT COUNT(DISTINCT Department) FROM Employees WHERE Employees.Employee = e.Employee) 
    END AS total_dept  
FROM Employees e
ORDER BY e.Employee, e.Department;

请参见demo