Я не могу понять, почему ваш (P2 - синий) результат показывает.Я переписал ваши образцы в виде SQL и создал то, что, как я думал, вы хотели (ожидая ожидаемого результата), а мой выводит только одну строку (P1 - красный)
create table dbo.Product (
ProductID int not null,
Name char(2) not null,
StateId char(2) not null,
CityId char(2) not null,
CountryId char(2) not null,
Price int not null,
Colour varchar(10) not null,
constraint PK_Product PRIMARY KEY (ProductID)
)
go
insert into dbo.Product (ProductID,Name,StateId,CityId,CountryId,Price,Colour)
select 1,'P1','S1','C1','C1',150,'Red' union all
select 2,'P2','S2','C2','C1',100,'Blue' union all
select 3,'P3','S1','C3','C1',200,'Green'
go
create table dbo.Settings (
SettingsID int not null,
StateId char(2) null,
CityId char(2) null,
CountryId char(2) null,
MaxPrice int not null,
MinPrice int not null,
constraint PK_Settings PRIMARY KEY (SettingsID)
)
go
insert into dbo.Settings (SettingsID,StateId,CityId,CountryId,MaxPrice,MinPrice)
select 1,null,null,'C1',1000,150 union all
select 2,'S1',null,'C1',2000,100 union all
select 3,'S1','C3','C1',3000,300
go
А теперь фактическое представление:
create view dbo.Products_Filtered
with schemabinding
as
with MatchedSettings as (
select p.ProductID,MAX(MinPrice) as MinPrice,MIN(MaxPrice) as MaxPrice
from
dbo.Product p
inner join
dbo.Settings s
on
(p.CountryId = s.CountryId or s.CountryId is null) and
(p.CityId = s.CityId or s.CityId is null) and
(p.StateId = s.StateId or s.StateId is null)
group by
p.ProductID
)
select
p.ProductID,p.Name,p.CityID,p.StateId,p.CountryId,p.Price,p.Colour
from
dbo.Product p
inner join
MatchedSettings ms
on
p.ProductID = ms.ProductID and
p.Price between ms.MinPrice and ms.MaxPrice
То, что я сделал, было объединение всех применимых настроек, а затем предположил, что мы применили самые ограничивающие настройки (поэтому возьмите указанную MAX MinPrice и MIN MaxPrice).
Использование этихправила, строка (P2 - синяя) исключена, поскольку единственная применимая настройка - настройка 1, минимальная цена которой равна 150.
Если я переверну ее, так что мы постараемся быть такими жевозможно (MIN MinPrice и MAX MaxPrice), затем возвращается (P1 - красный) и (P3 - зеленый) - но все еще нет (P2 - синий)