2013-01-22 41 views
1

我爲田AB以下數據,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 

我需要找到一對AB產生最大C值,然後選擇下一個最大值,以便它不包含AB。在上述數據中,第一次嘗試選擇1, 2,因爲99是最大值。第二次通過不包括1或2的所有配對,因此我們留下了3 3,4 34 4,第二個最大值爲4 4。這個過程一直持續,其結果是:

A B C 
-- -- -- 
1 2 99 
4 4 87 
3 3 9 

我怎樣才能做到這一點使用SQL?

+0

您正在使用什麼RDBMS? SQL Server,Oracle,MySQL,還有其他的東西? – LittleBobbyTables

+0

@littleBobbyTables我正在使用SQL Server – user2001212

+0

我爲您添加了'sql-server'標籤。將來,您應該使用適當的問題標籤以獲得最佳可見性,尤其是因爲此解決方案可能因RDBMS而異。 – LittleBobbyTables

回答

0
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 @[email protected]@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 @[email protected]@ROWCOUNT 
    end 

Select * from #tmp 
order by c desc 
Drop table #tmp 

有60萬行,你可以試試這個嘗試

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 
+0

非常感謝您的幫助,但是我很難完成600,000條記錄的實際數據庫上的代碼。是否有通過ID使用組來重複這些計算只能在一個ID內? – user2001212