我是SSMS的新手,我觉得这应该很容易,但我不知道如何做到这一点。为了简单起见,我重命名了我的表格。
SKU Reason
s1 r1
s1 r2
s1 r3
s2 r1
s2 r3
s3 r5
s3 r1
s3 r4
为了给出一个背景,SKU' s'由于三个原因被排除在外:r1,r2,r3。由于r1和r3的原因,排除了s2。由于r5,r1和r4的3个原因,s3被排除在外。
我可以根据SKU或Reason或两者过滤应用程序。如果我根据原因r1进行过滤,它应该返回由于r1而被排除的所有SKU,即上例中的s1,s2,s3。如果我根据原因r1和SKU s1进行过滤,它当前在结果中返回s1和r1,这就是我想要的。
现在,要求已经改变。如果我根据SKU s1的原因r1进行过滤,它不仅应该返回s1和r1,还应该是其他原因,因为sku s1被排除在外。即它应该返回s1 r1,s1 r2,s1 r3。但是,如果我按原因r5过滤SKU s1,它应该不返回,因为原因r5不排除SKU s1。
当前实施:
过滤条件:Sku s1和原因R1
SKU Reason
s1 r1
我想将其更改为:
过滤条件:Sku s1和原因R1
SKU Reason
s1 r1
s1 r2
s1 r3
答案 0 :(得分:1)
这是一个包含select语句的完整解决方案,可以尝试所有不同的条件:
declare @t table (sku varchar(2), reason varchar(2))
insert into @t values ('s1', 'r1')
insert into @t values ('s1', 'r2')
insert into @t values ('s1', 'r3')
insert into @t values ('s2', 'r1')
insert into @t values ('s2', 'r3')
insert into @t values ('s3', 'r5')
insert into @t values ('s3', 'r1')
insert into @t values ('s3', 'r4')
declare @sku_filter varchar(2)
declare @reason_filter varchar(2)
-- try each of these scenarios
select @sku_filter = 's1', @reason_filter = 'r1'
--select @sku_filter = 's1', @reason_filter = 'r5'
--select @sku_filter = null, @reason_filter = 'r1'
--select @sku_filter = 's1', @reason_filter = null
--select @sku_filter = null, @reason_filter = null
select sku, reason
from @t t
where (@sku_filter is not null and @reason_filter is not null and t.sku = @sku_filter and exists (select * from @t t where sku = @sku_filter and reason = @reason_filter))
or (@sku_filter is not null and @reason_filter is null and t.sku = @sku_filter)
or (@sku_filter is null and @reason_filter is not null and t.reason = @reason_filter)
or (@sku_filter is null and @reason_filter is null)
当条件在括号中组合在一起时,我发现读取它们要容易得多(例如@ param1不为空且@param2为空)。
答案 1 :(得分:0)
select * from table where sku in (select sku from table where sku='s1' and reason='r1')
答案 2 :(得分:0)
我认为你要构建这种形式的过滤器:
declare @sku varchar(50) = 's1'
declare @reason varchar(50) = 'r1'
SELECT * FROM TAB1 where (SKU=@sku )
and exists (
SELECT * FROM TAB1 where SKU=@sku AND Reason = @reason
)