Как установить приоритет записи на сервере sql? - PullRequest
0 голосов
/ 09 мая 2020

Хочу попробовать написать запрос. Мне нужно взять Targetvalue из таблицы #MetricTargets для MetricID, которые находятся в #Metrics.

{
CREATE TABLE #Metrics(
MetricId BiginT,
AccountId Bigint,
CountryId Bigint
)

INSERT INTO #Metrics(MetricId,AccountId,CountryId)select 8253,3,105

Create table #MetricTargets(
AccountId BIGINT,
MetricId BIGINT,
TargetValue BIGINT,
Countryid BIGINT
)

INSERT  INTO #MetricTargets(AccountId,TargetValue,MetricId,Countryid)SELECT 105,100,3,8253
INSERT  INTO #MetricTargets(AccountId,TargetValue,MetricId,Countryid)SELECT -1,80,3,8253
INSERT  INTO #MetricTargets(AccountId,TargetValue,MetricId,Countryid)SELECT 105,99,-1,8253 
}

CountryId = -1 и AccountId = -1 представляет для всех стран и учетных записей

Итак, я хочу получить Targetvalue для metricId, если AccountId и CountryId указаны в таблице #MetricTargets в первом приоритете, AccountId = Something и countryId = -1 - это 2-й приоритет, ACcountId = -1 и CountryId = SomeThing, затем 3-й. priority и AccountId = -1 и CountryId = -1, затем последний приоритет.

Я написал запрос ниже, но он дает все записи.

select M.TargetValue from #Metrics S   
LEFT JOIN #MetricsTargets M
ON  M.MetricId = S.MetricId AND (S.AccountId+M.AccountId<S.AccountId or S.AccountId = M.AccountId)
                               AND (S.CountryId+M.CountryId<S.CountryId or S.CountryId=M.CountryId)

1 Ответ

0 голосов
/ 09 мая 2020

Похоже, вы хотите сопоставить с -1 как подстановочный знак с более низким приоритетом. Я почти уверен, что боковое соединение делает то, что вы хотите:

select . . . 
from #Metrics m OUTER APPLY
     (select top (1) mt.*
      from #MetricsTargets mt
      where mt.MetricId = m.MetricId and
            m.account_id in (mt.account_id, -1) and
            m.country_id in (mt.country_id, -1)
      order by (case when mt.account_id = m.account_id and mt.country_id = m.country_id
                     then 1
                     when mt.account_id = m.account_id and mt.country_id = -1
                     then 2
                     when mt.account_id = -1 and mt.country_id = m.country_id
                     then 3
                     when mt.account_id = -1 and mt.country_id = -1
                     then 4
                end)
     ) mt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...