I have the following table with two fields namely a and b as shown below:
create table employe
(
empID varchar(10),
department varchar(10)
);
Inserting some records:
insert into employe values('A101','Z'),('A101','X'),('A101','Y'),('A102','Z'),('A102','X'),
('A103','Z'),('A103','Y'),('A104','X'),('A104','Y'),('A105','Z'),('A106','X');
select * from employe;
empID department
------------------
A101 Z
A101 X
A101 Y
A102 Z
A102 X
A103 Z
A103 Y
A104 X
A104 Y
A105 Z
A106 X
Note: Now I want to show the employee who is only and only belongs to the department Z
and Y
.
So according to the condition the only employee A103
should be displayed because of he only belongs
to the department Z
and Y
. But employee A101
should not appear because he belong to Z,X, and Y
.
Expected Result:
If condition is : Z
and Y
then result should be:
empID
------
A103
If condition is : Z
and X
then result should be:
empID
------
A102
If condition is : Z
,X
and Y
then result should be:
empID
------
A101
Note: I want to do it in the where
clause only (don't want to use the group by
and having
clauses), because I'm going to include this one in the other where
also.
try this
Solution using
where
clause:exists
checks if there are records for specificEmpId
that have total count ofdepartment
s equal to conditional count of only matchingdepartment
s and that it is also equal to the number ofdepartment
s provided to thein
clause. Also worth mentioning that here we applyhaving
clause without thegroup by
clause, on the whole set, but with already specified, only oneempID
.SQLFiddle
You can achieve this without the correlated subquery, but with the
group by
clause:SQLFiddle
You can also use another variation of
having
clause for the query above:SQLFiddle
For condition 1:z and y
For condition 1:z and x
For condition 1:z,y and x
Try this,
Count must based on number of conditions.
You can use
GROUP BY
withhaving
like this. SQL FiddleWithout
GROUP BY
andHaving
If you want to use any of the above query with other tables using a join you can use CTE or a derived table like this.
I know that this question has already been answered, but it was a fun problem to do and I tried to do it in a way that no one else has. Benefits of mine is that you can input any list of strings as long as each value has a comma afterwards and you don't have to worry about checking counts.
Note: Values must be listed in alphabetic order.
XML Solution with CROSS APPLY
Results: