Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Split data into groups

$
0
0

Hello, can anyone make a suggestion on how to make this work faster

Any advice would be great

USE [test]
GO
CREATE TABLE [dbo].[PeopleX](
[P1] [int] NULL,
[P2] [int] NULL,
[Grup] [int] NULL
) ON [PRIMARY]
insert into test.dbo.peoplex(p1,p2) values (1,2)
insert into test.dbo.peoplex(p1,p2) values (3,30000)
insert into test.dbo.peoplex(p1,p2) values (4,30001)
insert into test.dbo.peoplex(p1,p2) values (5,30002)
insert into test.dbo.peoplex(p1,p2) values (6,30003)
insert into test.dbo.peoplex(p1,p2) values (7,30004)
insert into test.dbo.peoplex(p1,p2) values (8,30005)
insert into test.dbo.peoplex(p1,p2) values (9,30006)
insert into test.dbo.peoplex(p1,p2) values (10,30007)

GO

Query that assigns group id



declare @totalgrup int
declare @idg int
declare @idg2 int

IF OBJECT_ID('tempDB..#temtb','U') IS NOT NULL
drop table #temtb

set @idg=1
set @idg2=1
set @totalgrup = (select COUNT(*) from test.dbo.PeopleX where test.dbo.PeopleX.grup is null)

while @totalgrup >0

begin

;WITH MINIGROUP (P1) AS
(select top 1  p1 from test.dbo.peoplex  pp where pp.grup is null
union all
select p2 from test.dbo.peoplex pp,  MINIGROUP where MINIGROUP.P1=pp.p1 and pp.grup is null
)

select * into #temtb from MINIGROUP
delete from #temtb where P1 is null

set @idg2 =(select top 1 isnull((select top 1 c.grup from test.dbo.PeopleX c,#temtb where (c.p1=#temtb.P1) or (c.p2=#temtb.P1) ),0))
if @idg2=0
update test.dbo.PeopleX set test.dbo.peoplex.grup = @idg where (test.dbo.PeopleX.p1 in (select * from #temtb)) or (test.dbo.PeopleX.p2 in (select * from #temtb))
else
update test.dbo.PeopleX set test.dbo.peoplex.grup = @idg2 where (test.dbo.PeopleX.p1 in (select * from #temtb)) or (test.dbo.PeopleX.p2 in (select * from #temtb))

set @idg=@idg+1

set @totalgrup = (select COUNT(*) from test.dbo.PeopleX where test.dbo.PeopleX.grup is null)

drop table #temtb

end

go


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>