Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of distinct records - SQL

Tags:

sql

db2

empid   projectId   TaskID
100     500           1
100     501           1
100     502           1
101     500           2
101     500          5
101     500          1
102     400          1
103     300          2
104     300          2
105     300          2  

I am trying to list the employees who works on multiple project only, based on project id . I tried distinct and GROUP BY . but am not able figure it exactly.

from the above table am expecting a result like this

 empid   projectId  
    100     500         
    100     501          
    100     502 
like image 798
zod Avatar asked Oct 03 '11 16:10

zod


2 Answers

Try this (revised code)

SELECT DISTINCT EmpId, ProjectId
FROM TableX
WHERE EmpId IN 
(
    SELECT EmpId
    FROM TableX
    GROUP BY EmpId
    HAVING COUNT (DISTINCT ProjectId) > 1
)

This should give you

EmpId       ProjectId
----------- -----------
100         500
100         501
100         502

3 row(s)

Edit Content added for OPs additional question in the comments

A count giving you distint ProjectIds would mean that the GROUP BY would be at an EmpId level and no need for a subquery

SELECT EmpId, Count (Distinct ProjectId) Projects
FROM TableX
GROUP BY EmpId

To get a count of projects for all employees with multiple projects, do the following

SELECT EmpId, Count (Distinct ProjectId) Projects
FROM TableX
GROUP BY EmpId
Having Count (Distinct ProjectId) > 1
like image 99
Raj More Avatar answered Oct 11 '22 21:10

Raj More


You could also use a windowed COUNT():

WITH counted AS (
  SELECT
    empid,
    projectId,
    COUNT(DISTINCT projectId) OVER (PARTITION BY empid) AS ProjectCount
  FROM atable
)
SELECT DISTINCT
  empid,
  projectId
FROM counted
WHERE ProjectCount > 1

References:

  • OLAP functions

  • WITH clause

like image 21
Andriy M Avatar answered Oct 11 '22 21:10

Andriy M