對不起後期的帖子,我在休息時開始了這段時間,並被取消。
首先,讓我們用你的數據創建一個測試環境。
-- Just playing
use tempdb;
go
-- Create a test table
create table test
(
group1 varchar(4),
group2 varchar(4),
group2_val int
);
go
-- Add data
insert into [test] values
('x','a','1'),
('y','a','6'),
('g','a','5'),
('y','b','3'),
('g','b','1'),
('x','c','7'),
('g','d','9'),
('g','d','5'),
('g','e','2'),
('g','e','2');
go
-- Show data
select * from [test];
go
其次,我用三個常見的表達式解決了它。每一個建立在彼此之上。
-- Raw data with rank
with cteRawData
as
(
select group2, group1, group2_val,
rank() over
(
partition by group2 order by
case group1
when 'g' then 1
when 'y' then 2
when 'x' then 3
else 0
end
) as drank
from [test]
),
-- Get distinct topmost rank
cteRankData as
(
select distinct group2, group1, group2_val
from cteRawData where drank = 1
),
-- Find all singleton records
cteRankCount as
(
select group2, group1
from cteRankData
group by group2, group1
having count(*) = 1
)
-- Return the results of a inner join
select a.group1, a.group2, a.group2_val
from
cteRankData a inner join cteRankCount b
on a.group2 = b.group2 and a.group1 = b.group1
最後但並非最不重要的,預期的結果。
這有助於給我一些建議。 – Piyush