-1

I have the below table

Table 1

Id   WFID  data1   data2
1    12    'd'     'e'
1    13    '3'     '4f'
1    15    'e'     'dd'
2    12    'f'     'ee'
3    17    'd'     'f'
2    17    'd'     'f'
4    12    'd'     'f'
5    20    'd'     'f'

From this table I just want to select the rows which has 12 and 17 only exclusively. Like from the table I just want to retrieve the distinct id's 2,3 and 4. 1 is excluded because it has 12 but also has 13 and 15. 5 is excluded because it has 20.

  • 2 in included because it has just 12 and 17.
  • 3 is included because it has just 17
  • 4 is included because it has just 12
halfer
  • 19,824
  • 17
  • 99
  • 186
SP1
  • 1,182
  • 3
  • 22
  • 47

2 Answers2

3

If you just want the list of distinct ids that satisfy the conditions, you can use aggregation and filter with a having clause:

select id
from mytable
group by id
having max(case when wfid not in (12, 17) then 1 else 0 end) = 0

This filters out groups that have any wfid other than 12 or 17.

If you want the entire corresponding rows, then window functions are more appropriate:

select
from (
    select t.*,
        max(case when wfid not in (12, 17) then 1 else 0 end) over(partition by id) flag
    from mytable t
) t
where flag = 0
GMB
  • 216,147
  • 25
  • 84
  • 135
1

You really need to start thinking in terms of sets. And it helps everyone if you provide a script that can be used to experiment and demonstrate. Here is another approach using the EXCEPT operator. The idea is to first generate a set of IDs that we want based on the filter. You then generate a set of IDs that we do not want. Using EXCEPT we can then remove the 2nd set from the 1st.

declare @x table (Id tinyint, WFID tinyint, data1 char(1), data2 varchar(4));

insert @x (Id, WFID, data1, data2) values
(1,    12,    'd',     'e'),
(1,    13,    '3',     '4f'), 
(1,    15,    'e',     'dd'),
(2,    12,    'f',     'ee'),
(3,    17,    'd',     'f'),
(2,    17,    'd',     'f'),
(4,    12,    'd',     'f'),
(2,    12,    'z',     'ef'),
(5,    20,    'd',     'f');

select * from @x 
select id from @x where WFID not in (12, 17);

select id from @x where WFID  in (12, 17)
except
select id from @x where WFID not in (12, 17);

Notice the added row to demonstrate what happens when there are "duplicates".

SMor
  • 2,830
  • 4
  • 11
  • 14
  • Thank you so much SMor..next time I ll make sure I provide a playgroup script..I tried doing one in SQL Fiddle but I kept getting error of Table not exist even though I build the schema..I ll try harder next time. – SP1 Nov 05 '20 at 03:46