一种方法是使用窗口函数来判断您的条件,然后可以使用CTE将其作为条件apply.
这将创建您想要的数据,然后将其插入到您 Select 的表中是很容易的.
create table Test (Id int, [Type] varchar(3), [Key] int, [Value] int);
insert into Test (Id, [Type], [Key], [Value])
values
(1, 'Cat', 10, 5),
(1, 'Cat', 9, 2),
(2, 'Dog', 10, 5),
(1, 'Cat', 8, 4),
(1, 'Cat', 6, 3),
(2, 'Dog', 8, 4),
(2, 'Dog', 6, 3),
(3, 'Cat', 13, 5),
(3, 'Cat', 10, 0),
(3, 'Cat', 8, 0);
with cte as (
select *
, sum(case when [Key] = 10 and [Value] = 5 then 1 else 0 end) over (partition by Id) Cond1
, sum(case when [Key] = 8 and [Value] = 4 then 1 else 0 end) over (partition by Id) Cond2
, sum(case when [Key] = 6 and [Value] = 3 then 1 else 0 end) over (partition by Id) Cond3
, sum(case when [Key] = 9 then 1 else 0 end) over (partition by Id) HasFee
from Test
)
select Id, [Type], HasFee
from cte
where Cond1 = 1 and Cond2 = 1 and Cond3 = 1
group by Id, [Type], HasFee;
返回:
Id |
Type |
HasFee |
1 |
Cat |
1 |
2 |
Dog |
0 |
注意:如果您以这种格式(DDL+DML)提供样本数据,人们将更容易获得帮助.
db<>fiddle个