Selecting rows from a table with specific values per id

匆匆过客 提交于 2021-02-11 14:16:54

问题


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

Any help is much appreciated.


回答1:


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



回答2:


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".



来源:https://stackoverflow.com/questions/64686164/selecting-rows-from-a-table-with-specific-values-per-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!