select ssn, count(*)
from (
select ssn, employee_id, is_active
from employee
where is_active ='Y'
)
group by ssn
having count(*) > 1
I want to modify this query to find all ssn
's that exist in the table more than once BUT with different employee_id
's, with at least one record having is_active
of Y.
If you want all the details then:
SELECT ssn,
employee_id,
is_active
FROM (
SELECT ssn,
employee_id,
is_active,
COUNT( DISTINCT employee_id ) OVER ( PARTITION BY ssn ) AS num_emps,
COUNT( CASE is_active WHEN 'Y' THEN 1 END ) OVER ( PARTITION BY ssn )
AS num_active
FROM employee
)
WHERE num_emps > 1
AND num_active > 0
If you just want the ssn
s then:
SELECT ssn
FROM employee
GROUP BY ssn
HAVING COUNT( DISTINCT employee_id ) > 1
AND COUNT( CASE is_active WHEN 'Y' THEN 1 END ) > 0;
No subquery or CTE is needed, just group by
and having
:
select ssn, count(*)
from employee
group by ssn
having min(employee_id) <> max(employee_id) and
sum(case when is_active ='Y' then 1 else 0 end) >= 1;
You could use windowed COUNT
to get number of distinct employees and SUM
to handle at least on active:
WITH cte AS(
select ssn, employee_id,
COUNT(DISTINCT employee_id) OVER(PARTITION BY ssn) AS cnt,
SUM(CASE WHEN is_active ='Y' THEN 1 ELSE 0 END) OVER(PARTITION BY ssn) AS s_active
from employee
)
SELECT *
FROM cte
WHERE cnt > 1 AND s_active > 1;
If I'm understanding correctly this should do
select TMP.*
from (
select CASE WHEN MIN(employee_id) OVER( PARTITION BY ssn) <>
MAX(employee_id) OVER( PARTITION BY ssn) THEN 'Y'
ELSE 'N'
END AS hasMultipleDistinctEmployees,
CASE WHEN MAX(CASE WHEN is_active = 'Y' THEN 1 ELSE 0 END) OVER
( PARTITION BY ssn ) = 1 THEN 'Y'
ELSE 'N'
END AS hasAtLeaseOneActive,
ssn, employee_id, is_active
from employee
) TMP
WHERE hasMultipleDistinctEmployees = 'Y'
AND hasAtLeaseOneActive = 'Y'
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.