Sql, checking if a value appears greater than 2x in the table

if I have a circuit that goes something like this:

peoples (person's name, etc.) jobs (personNumber, jobNumber)

and a person can have more than one task, how to write a request that tells me if a person has less than two tasks

select personNumber from peoples
where personNumber not in
(
    select personNumber from jobs
    where ??personNumber appears two times or more in jobs??
);

thanks to someone who takes time to help

+3
source share
3 answers

Using:

SELECT p.*
  FROM PEOPLES p
 WHERE NOT EXISTS(SELECT NULL
                    FROM JOBS j
                   WHERE j.personnumber = p.personnumber
                  HAVING COUNT(DISTINCT j.jobnumber) > 1)
+3
source

The easiest way to do this is to use the aggregated COUNT () function with the GROUP BY clause.

SELECT personNumber
FROM jobs
GROUP BY personNumber
HAVING count(*) < 2

, , . , , , .

+4
select personNumber from
(
    select personNumber,count(*) as numJobs from jobs group by personNumber
) as jobCounts where numJobs<2
0
source

Source: https://habr.com/ru/post/1758575/


All Articles