我正在尝试过滤表1:
Table1
Region mCode pCode
Europa AD E
Rest of the world AD O
East Europa AE O
Outside AE L
Rest of the world AE E
Asia AF O
North America AG D
Rest of the world AG L
North America AI D
Rest of the world AI L
America AI L
pCode(D,L,E,O)有四个不同的值,可以重复mCode。
根据以下情况,我仅需要获得mCode具有优先级为pCode的那些行:
Highest priority pCode = D
Second priority pCode = L
Third priority pCode = E
last priority pCode = O
例如,mCode'AE'出现在3行中,而pCode在不同的行中分别是'O','L'和'E'。根据pCode优先级,结果将显示pCode为第二优先级“ L”的行,因为没有“ AE”的行具有高于“ L”的优先级。其余的行并不重要。
所需的结果将mCode作为唯一值:
Region mCode pCode
Europa AD E
Outside AE L
Asia AF O
North America AG D
North America AI D
您可以使用row_number()为每个mCode
分配优先级,然后仅过滤优先级最高的优先级
select *
from
(
select *, p = row_number() over (partition by mCode
order by case when pCode = 'D' then 1
when pCode = 'L' then 2
when pCode = 'E' then 3
when pCode = 'O' then 4
end)
from Table1
) d
where d.p = 1
将带有ROW_NUMBER()
表达式的窗口函数CASE
使用为>]
SELECT Region, mCode, pCode
FROM
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY mCode ORDER BY CASE pCode WHEN 'D' THEN 0
WHEN 'L' THEN 1
WHEN 'E' THEN 2
WHEN 'O' THEN 3
END) RN
FROM
(
VALUES
('Europa' ,'AD', 'E'),
('Rest of the world' ,'AD', 'O'),
('East Europa' ,'AE', 'O'),
('Outside' ,'AE', 'L'),
('Rest of the world' ,'AE', 'E'),
('Asia' ,'AF', 'O'),
('North America' ,'AG', 'D'),
('Rest of the world' ,'AG', 'L'),
('North America' ,'AI', 'D'),
('Rest of the world' ,'AI', 'L'),
('America' ,'AI', 'L')
) T(Region, mCode, pCode)
) TT
WHERE RN = 1;
] >>