在sql上显示列值及其计数

epfja78i  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(313)

我只想问你一个关于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

我有一个非常大的表(有许多列和许多数据),所以我认为这可以是一个“优化”,不是吗?我的意思是,没有必要在所有的行中存储整个部门。只要放一次就够了。没问题,如果在这之后我留下了空栏。但我不知道是否有可能在sql中做这样的事情。
那么,我该怎么解决这个问题呢?我试过了,但似乎不可能把count(column)和同一列结合起来。。。
先谢谢你

eh57zj3b

eh57zj3b1#

这可能就是你要找的

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

zyfwsgd62#

mysql 8.0支持窗口化 COUNT :

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

db<>小提琴演示
您甚至可以有第二个结果集(我建议将表示问题留给应用程序层):

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<>小提琴演示

sq1bmfud

sq1bmfud3#

对于第2版:

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;

查看演示

相关问题