Declare @State varchar(2)
Create Table #tmpSALES (State varchar(2), SalesPeople varchar(60))
Declare State_Cursor Cursor for
Select distinct state from SALES
Open State_Cursor
Fetch Next From State_Cursor into @State
While @@Fetch_Status = 0
Begin
Declare @SALES1 varchar(20)
Declare @SALES2 varchar(20)
Declare @SALES3 varchar(20)
set @SALES1 = select top 1 SALESPERSON from SALES where State = @State
set @SALES2 = select top 1 SALESPERSON from SALES where State = @State and SALESPERSON <> @SALES1
set @SALES3 = select top 1 SALESPERSON from SALES where State = @State and SALESPERSON <> @SALES1 and SALESPERSON <> @Sales2
Insert Into #tmpSALES values (@State, (@SALES1 + ',' + @SALES2 + ',' + @SALES3))
Fetch Next from State_Cursor into @State
End
Close State_Cursor
Deallocate State_Cursor
Select * from #tmpSALES
Drop Table #tmpSALES
select @@Version
set @SALES1 = (select top 1 SALESPERSON from SALES where State = @State)
set @SALES2 = (select top 1 SALESPERSON from SALES where State = @State and SALESPERSON <> @SALES1)
set @SALES3 = (select top 1 SALESPERSON from SALES where State = @State and SALESPERSON <> @SALES1 and SALESPERSON <> @Sales2)
DROP TABLE #TempTable
Create Table #TempTable
([ID] int Identity,
[State] Varchar(30)
)
DROP TABLE #TempHolding
Create Table #TempHolding
([ID] int Identity,
[State] Varchar(500),
[Details] Varchar(500)
)
Insert into #TempTable
SELECT DISTINCT STATE FROM [dbo].[TABLE_NAME]
Declare @SALES1 varchar(20)
Declare @SALES2 varchar(20)
Declare @SALES3 varchar(20)
Declare @State varchar(20)
DECLARE @Loop int
Set @Loop = 1
While @Loop <= (select count(*) from #TempTable)
Begin
Set @SALES1 = (SELECT TOP 1 SALESPERSON FROM [dbo].[TABLE_NAME] WHERE STATE = (select state from #TempTable where id = @loop) ORDER BY [State],[Amount] DESC)
Set @SALES2 = (SELECT TOP 1 SALESPERSON FROM [dbo].[TABLE_NAME] WHERE STATE = (select state from #TempTable where id = @loop) and SALESPERSON <> @SALES1 ORDER BY [State],[Amount] DESC)
Set @SALES3 = (SELECT TOP 1 SALESPERSON FROM [dbo].[TABLE_NAME] WHERE STATE = (select state from #TempTable where id = @loop) and SALESPERSON <> @SALES1 and SALESPERSON <> @Sales2 ORDER BY [State],[Amount] DESC)
SET @State = (select state from #TempTable where id = @loop)
Insert into #tempholding
values(@State,@SALES1 + ',' + @SALES2 + ',' + @SALES3)
SET @loop = @loop + 1
End
Select * from #tempholding
Open in new window