salamanka44
salamanka44

Reputation: 944

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

Upvotes: 1

Views: 85

Answers (3)

forpas
forpas

Reputation: 164204

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

Upvotes: 0

Lukasz Szozda
Lukasz Szozda

Reputation: 176189

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

Upvotes: 1

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30665

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;

Upvotes: 2

Related Questions