该表包含PID和相应的值。具有相同值的PID应该分配相同的组ID。 A,B,D直接连接(值= ABC),并且C与D连接(值= GHI),因此A,B,C和D都属于同一组。
PID Value
--------------
A101 ABC
A101 XYZ
B101 ABC
C101 GHI
C101 DEF
D101 ABC
D101 GHI
E101 KLM
F101 MNO
预期结果:
PID GroupID
--------------
A101 1
B101 1
C101 1
D101 1
E101 2
F101 3
我尝试了以下查询,但未成功:
with cte as (
select PID, Value, Rank() OVER(ORDER BY Value) rn
from t
union all
select t.PID, cte.Value, cte.rn
from t join cte
on t.Value = cte.Value and
t.PID < cte.PID
)
select *
from cte
是否可以在SQL Server 2012/2014中修复查询并编写更高效的查询(约100万行)?
答案 0 :(得分:0)
尝试以下操作:
declare @tab table (PID varchar(10), Val varchar(100))
insert into @tab select 'A101', 'ABC'
insert into @tab select 'A101', 'XYZ'
insert into @tab select 'B101', 'ABC'
insert into @tab select 'C101', 'GHI'
insert into @tab select 'C101', 'DEF'
insert into @tab select 'D101', 'ABC'
insert into @tab select 'D101', 'GHI'
insert into @tab select 'E101', 'KLM'
insert into @tab select 'F101', 'MNO'
select PID, dense_rank() over (order by group_id) GROUP_ID
from
(
select x.PID, min(t.num) group_id from @tab X
join (select val, dense_rank() over (order by val) num from @tab)t on t.Val = X.Val
group by x.PID
)t2
order by 2