SQL Server Arrange cities based on their ranking [closed]

wixjitnu  于 2023-02-18  发布在  其他
关注(0)|答案(1)|浏览(101)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed yesterday.
Improve this question

I need to display ranking along with city based on city selection. Suppose if someone select Nagpur, we need to show the predecessor city, selected city and followed by successor city with their respective ranking.

Criteria

  1. If someone selects Mumbai then, No Data, Mumbai-1, Delhi-2
  2. If someone selects Delhi then, Mumbai-1, Delhi-2, Lucknow-3
  3. If someone selects Nagpur then, Lucknow-3, Nagpur-3, Pune-3 (based on city's sorting order alphabetically, if there are multiple cities having same ranking)
  4. If someone selects Kanpur then, Patna-7, kanpur-8, No Data.

The data is in this format:

Can someone help to achieve this? I am using SQL Server 2016

bxgwgixi

bxgwgixi1#

It may not be the best solution, but it will be useful for now. I recommend that you always add an id to the tables and the names of the fields can be easily identified to which table they belong

DROP TABLE #TableTempRankingCity
 DECLARE @Id INT;

 SELECT ROW_NUMBER() OVER(
 ORDER BY [City]) AS fila, *
 INTO #TableTempRankingCity
 FROM RankingCiudades
 ORDER BY Rank,City

 --SELECT * FROM #TableTempRankingCity
 SELECT @Id = fila
 FROM #TableTempRankingCity
 WHERE City = 'Lucknow'

 SELECT 
    City 
    ,Rank
 FROM #TableTempRankingCity 
 WHERE fila IN (@Id-1,@Id+1,@Id+2)

相关问题