How to get data from a table

I need to select the name of the player, the name of the captain from the structure of the table below.

Table structure

consists in the following.

create table #temp (Playerid int, PlayerName varchar (100), CaptainId int)

PlayerId     PlayerName     CaptainId
--------------------------------------
1            Dhoni          NULL
2            Sachin         1
3            Rahul          1

I need to select the name of the player along with his captain name from this table. Can anyone

+3
source share
4 answers

There are various ways to answer these requests:

select playerName, (select t2.playername from #temp t2 where t2.playerid = t.captainid  ) from #temp t


select t1.playername , t2.playername captain from #temp t1 left join #temp t2 on t1.captainid = t2.playerid
+1
source

Assuming CaptainId is referencing PlayerId in the same table, you need the following:

select t.PlayerName, t2.PlayerName as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId

If you want to exclude players without a captain, you will make this inner join.

Of course you can convert zero:

select t.PlayerName, isnull(t2.PlayerName,'None') as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId
+1

self join table.

-

SELECT p.PlayerName,
 c.PlayerName CaptainName
FROM #temp p LEFT JOIN
 #temp c ON p.CaptainId = c.PlayerId
+1
SELECT PlayerName, CaptainName 
FROM PlayerTable INNER JOIN CaptainTable
ON PlayerTable.CaptainID=CaptainTable.CaptainID
WHERE CaptainName = 'your query'
0

Source: https://habr.com/ru/post/1775810/


All Articles