-- -- Symmetric version -- DROP TABLE ResultR1R2 CREATE TABLE [dbo].[ResultR1R2] ( [tid1] int NOT NULL, [tid2] int NOT NULL, [sim] float NOT NULL, [S] int NOT NULL, PRIMARY KEY (S,tid1,tid2), FOREIGN KEY (tid1) REFERENCES R1, FOREIGN KEY (tid2) REFERENCES R2, ) GO DECLARE @S int DECLARE @I int DECLARE @UPPERLIMIT int -- The upper limit in the sample size will be 2^@UPPERLIMIT SET @I=0 SET @UPPERLIMIT=8 WHILE @I <= @UPPERLIMIT BEGIN SET @S=POWER(2, @I) BEGIN TRANSACTION INSERT INTO ResultR1R2(tid1,tid2,sim,S) SELECT tid1,tid2,AVG(sim),S FROM ( SELECT tid1,tid2,sim,S FROM ResultR1sR2 WHERE ResultR1sR2.S=@S UNION ALL SELECT tid1,tid2,sim,S FROM ResultR2sR1 WHERE ResultR2sR1.S=@S ) A GROUP BY tid1,tid2,S COMMIT TRANSACTION CHECKPOINT SET @I = @I+1 END GO