Question

I've been searching for a little while now trying to find a way to use rank() as a column to use for a join. I've looked at a few resources, here, here, and here. And none of these match exactly what I want to accomplish.

What I have been given is a string of id's deliminated by a space. I need to assign these ids in no particular order to my Animal table. I am working inside a platform that will only allow me to do this in sql, so using a high level programming language is not an option.

Here is an example.

I want to take my string, "345345 345436 678768" parse it out and fill out my table like so

|Name     |ID    |
------------------
|Monkey   |345345| 
|Bird     |345436| 
|Horse    |678768| 

I have already written a function that takes my string, breaks it apart and numbers it. So when I give my split function "345345 345436 678768" I get:

|Num |ID    |
-------------
|1   |345345| 
|2   |345436| 
|3   |678768| 

So now I want to do something like this:

select name, (rank() over( order by name)) as rank_num
from dbo.Split(" ", "345345 345436 678768") split, animal
where num = rank_num

But I get "Invalid column name 'rank_num'

Was it helpful?

Solution

I think this is what you need.

SELECT a.* 
FROM 
(
    select name, (rank() over( order by name)) as rank_num
    from animal
) as a
JOIN dbo.Split(" ", "345345 345436 678768") split ON split.num = a.rank_num
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top