简体   繁体   中英

Display column values and their count on SQL

I just want to ask you please this question on SQL.

Let's consider this EMPLOYEE table :

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

What I want to display is for each employee, all distinct departments (without duplicates) AND the total number of those distinct departments. So, something like this :

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

If possible, I would even prefer something like these :

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

I have a very big table (with many columns and many data) so I thought this can be an "optimisation", no ? I mean, there is no need to store the total_dept in all rows. Just put it once it's sufficient. No problem if after this I left the column empty. But I don't know if it's possible to do such thing in SQL.

So, how can I fix this please ? I tried but it seems impossible to combine count(column) with the same column...

Thank you in advance

This might be what you are looking for

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

MySQL 8.0 supports windowed COUNT :

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

db<>fiddle demo


You could even have second resulset(I recommend to leave presentation matter to apllication layer):

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

For the 2nd version:

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;

See the demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM