0

Using SQL server 2012.

I am trying to rank some results using a cursor but having problems.

The code is as follows.

declare @companyid int
declare @tempTable table(rank int, companyname nvarchar(50), hedgevalue float)
declare c cursor for select id from gascompanies

open c

fetch next from c into @companyID

while @@FETCH_STATUS=0 begin
--insert into @tempTable([rank], companyName, hedgeValue) 
select rank=count(*), gc.companyName as companyName, hedgevalue
from DayAheadSettings DAS
left outer join GasCompanies GC ON gc.ID = das.CompanyID
left outer join gashedges on gc.id = GasHedges.CompanyID
where nominatehedge = 0 and gc.ID = @companyid and hedgeDate = convert(date, GETDATE() + 1)
group by CompanyName, hedgevalue

fetch next from c into @companyid
end
close c
deallocate c

This produces the following results as there are 3 company ID's

result set

The table above has the rank of 1 twice and I would like RWET to be 1 and JPMorgan 2 and if there was a third then 3. (ideally I wouldn't want the third result to show unless there is data)

If I ran the query and there was only one with data, JPMorgan for example then I would like the rank to be 1.

Hope that all makes sense.

Community
  • 1
  • 1
Silentbob
  • 2,805
  • 7
  • 38
  • 70

1 Answers1

0

After looking at this for sometime I had a epiphany I changed the rank to an ID column that auto incremented.

This solved my issue.

Silentbob
  • 2,805
  • 7
  • 38
  • 70