I have a table like this.
PersonID, KvalifikationId 1 1 1 2 1 3 2 1 2 3
I want to write an SQL query that returns all persons who do not have kvalifikation 2.
I wrote
SELECT DISTINCT PersonID where NOT KvalifikationID = 2
But this returns both person 1 and person 2. How to make a choice that only returns personId that does not have kval2?
Try it,
SELECT DISTINCT PersonID FROM tableName WHERE PersonID NOT IN ( SELECT PersonID FROM tableName WHERE KvalifikationId = 2 )
SELECT DISTINCT person_id FROM tableName t1 WHERE not exists ( select 1 from tableName where person_id = t1.person_id and KvalifikationId = 2 )
Declare @t table(PersonID int,KvalifikationId int) Insert Into @t Select 1 ,1 Insert Into @t Select 1, 2 Insert Into @t Select 1,3 Insert Into @t Select 2 ,1 Insert Into @t Select 2,3 Select PersonId From @t Except Select PersonID From @t where KvalifikationId = 2
PersonId 2
Person, N: N , distinct, -- , . (, PersonID pk Person)
Person
distinct
PersonID
SELECT PersonID FROM tblPerson WHERE NOT EXISTS ( SELECT NULL FROM tblPersonKvalifikation WHERE KvalifikationId = 2 AND tblPerson.PersonID = tblPersonKvalifikation.PersonID )
.SELECT DISTINCT PersonID from tableNameWHERE KvalifikationId NOT IN ('2');