Sql server 递归选择唯一的最大值
我有以下字段的数据Sql server 递归选择唯一的最大值,sql-server,recursion,max,Sql Server,Recursion,Max,我有以下字段的数据A,B,C: A B C -- -- -- 1 1 90 1 2 99 1 3 75 2 1 60 2 2 54 2 3 95 3 1 85 3 2 80 3 3 9 4 1 80 4 2 85 4 3 86 4 4 87 我需要找到产生最大C值的A和B对,然后选择下一个最大值,使其不包含A或B。在上述数据中,第一次尝试选择1,2,因为99是最大值。第二次通过排除所有1或2的对,因此剩下33、43和44,第二个最大值是4
A
,B
,C
:
A B C
-- -- --
1 1 90
1 2 99
1 3 75
2 1 60
2 2 54
2 3 95
3 1 85
3 2 80
3 3 9
4 1 80
4 2 85
4 3 86
4 4 87
我需要找到产生最大C
值的A
和B
对,然后选择下一个最大值,使其不包含A
或B
。在上述数据中,第一次尝试选择1,2
,因为99
是最大值。第二次通过排除所有1或2的对,因此剩下33
、43
和44
,第二个最大值是44
。该过程继续进行,结果是:
A B C
-- -- --
1 2 99
4 4 87
3 3 9
如何使用SQL实现这一点
declare @a table (a int,b int,c int)
insert into @a values (1, 1, 90)
,(1, 2, 99)
,(1, 3, 75)
,(1, 3, 75)
,(2, 1, 60)
,(2, 2 ,54)
,(2, 3, 95)
,(3, 1, 85)
,(3, 2, 80)
,(3, 3, 9)
,(4, 1, 80)
,(4, 2, 85)
,(4, 3 ,86)
,(4, 4, 87);
Declare @rct int
Select top 1 *
into #tmp
from @a
Order by c desc
Select @rct=@@ROWCOUNT
While @rct>0
begin
Insert into #tmp
Select Top 1 a.*
from @a a
Left Join #tmp on #tmp.A=a.A or #tmp.B=a.B or #tmp.b=a.A or #tmp.A=a.b
Where #tmp.a is null and #tmp.b is null
Order by C desc
Select @rct=@@ROWCOUNT
end
Select * from #tmp
order by c desc
Drop table #tmp
对于600000行,您可以尝试此尝试
declare @a table (a int,b int,c int)
insert into @a values (1, 1, 90)
,(1, 2, 99)
,(1, 3, 75)
,(1, 3, 75)
,(2, 1, 60)
,(2, 2 ,54)
,(2, 3, 95)
,(3, 1, 85)
,(3, 2, 80)
,(3, 3, 9)
,(4, 1, 80)
,(4, 2, 85)
,(4, 3 ,86)
,(4, 4, 87);
Declare @rct int
Select a,b,c
into #work
from @a -- your big table
CREATE NONCLUSTERED INDEX [i_a] ON #work (a)
CREATE NONCLUSTERED INDEX [i_b] ON #work (b)
CREATE NONCLUSTERED INDEX [i_c] ON #work (c)
Select top 1 *
into #tmp
from #work
Order by c desc
Select *
into #final
from #tmp
Delete #work
from #tmp
where #work.a=#tmp.a or #work.b=#tmp.a or #work.a=#tmp.b or #work.b=#tmp.b
While (Select COUNT(*) from #work) >0
begin
delete from #tmp
insert into #tmp
Select top 1 *
from #work
Order by c desc
insert into #final
Select *
from #tmp
Delete #work
from #tmp
where #work.a=#tmp.a or #work.b=#tmp.a or #work.a=#tmp.b or #work.b=#tmp.b
end
drop table #work
drop table #tmp
Select * from #final
drop table #final
您正在使用什么RDBMS?SQL Server,Oracle,MySQL,还有别的吗?@littleBobbyTables我正在使用SQL Server我已经为您添加了
SQL Server
标记。将来,您应该使用适当的问题标签以获得最佳可见性,特别是因为此解决方案可能因RDBMS而异。谢谢,这非常有用,但我很难在一个包含600000条记录的真实数据库上完成代码。是否有某种方法可以使用group by ID在一个ID内重复这些计算?