Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Rando
Starting Member
11 Posts |
Posted - 2010-12-21 : 09:29:43
|
Hello,I have a situation which I've not encountered before since I'm fairly new to SQL. I have a table that contains every single user within a building. Each user has a supervisor ID # that indicates who they report to. Since I have their ID # I would like to re-query the same table and get their name. How can I do this?Table Data:ID Name SupervisorID12345 Susie Tester 9875154321 Iam Testy 54654 Tom McTest 46546 Sammy Sample 5465498751 Mark Debug 65465 Super Shopper 12345 Expected Results:ID Name Supervisor12345 Susie Tester Mark Debug54321 Iam Testy 54654 Tom McTest46546 Sammy Sample Tom McTest98751 Mark Debug 65465 Super Shopper Susie Tester I'm not too concerned with users not having a supervisor ID #. Thanks for any help |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2010-12-21 : 11:25:55
|
| You can join a table to itselfJimDECLARE @table TABLE(id int,fName varchar(20),SupervisorID int)INSERT INTO @TableSELECT 12345,'Susie Tester', 98751 UNION ALLSELECT 54321,'Iam Testy', null UNION ALLSELECT 54654,'Tom McTest', null UNION ALLSELECT 46546,'Sammy Sample', 54654 UNION ALLSELECT 98751,'Mark Debug', null UNION ALLSELECT 65465,'Super Shopper', 12345SELECT t1.ID,t1.fName,[SuperVisor] = t2.fNameFROM @table t1LEFT JOIN @table t2 ON t1.SuperviSorID = t2.IDEveryday I learn something that somebody else already knew |
 |
|
|
|
|
|
|
|