从每个 id 具有特定值的 table 中选择行

Selecting rows from a table with specific values per id

我有以下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'

由此 table 我只想 select 仅包含 12 和 17 的行。就像 table 一样,我只想检索不同 ID 的 2,3 和 4。1 被排除在外,因为它有 12,但也有 13 和 15。5 被排除在外,因为它有 20.

如果您只想要满足条件的不同 id 的列表,您可以使用带有 having 子句的聚合和过滤器:

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

这会过滤掉除 1217.

之外的任何 wfid

如果你想要整个对应的行,那么window函数更合适:

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

你真的需要开始考虑集合了。如果您提供可用于实验和演示的脚本,它对每个人都有帮助。这是使用 EXCEPT 运算符的另一种方法。思路是先根据过滤器生成一组我们想要的ID。然后您生成一组我们不想要的 ID。使用 EXCEPT 然后我们可以从第一组中删除第二组。

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);

请注意添加的行以演示存在“重复项”时会发生什么。