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 |
|
mike123
Master Smack Fu Yak Hacker
1462 Posts |
Posted - 2007-05-03 : 04:19:27
|
| Hi,I'm looking to write a "friends of friends" query and I'm not exactly sure what the best way to do it is.I have a table as such and want to be able to select level 2 friends basically. I want this list to be a unique list of the userID's, and if its possible have a count(*) as well.Thanks very much for any assistance! :)mike123For exampleuserID/friendID1 / 5001 / 4001 / 300500 / 22500 / 33400 / 22300 / 11The results returned would befriendID223311OR friendID / count22 /233 /111 /1CREATE TABLE [dbo].[tblFriends]( [UserID] [int] NOT NULL, [FriendID] [int] NOT NULL) |
|
|
pbguy
Constraint Violating Yak Guru
319 Posts |
Posted - 2007-05-03 : 04:48:48
|
| declare @tt table (uid int , fid int)insert @ttselect 1, 500 union allselect 1, 400 union allselect 1, 300 union allselect 500, 22 union allselect 500, 33 union allselect 400, 22 union allselect 300, 11select fid, Count = Count(uid) from (select * from @tt where uid in (select fid from @tt where uid =1)) a group by fid |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-05-03 : 05:29:16
|
| [code]-- prepare sample datadeclare @tt table (uid int, fid int)insert @ttselect 1, 500 union allselect 1, 400 union allselect 1, 300 union allselect 500, 22 union allselect 500, 33 union allselect 400, 22 union allselect 300, 11-- show the expected outputselect t2.fid as friendid, count(*) as countfrom @tt as t1inner join @tt as t2 on t2.uid = t1.fidwhere t1.uid = 1group by t2.fidorder by 2 desc, 1[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
spirit1
Cybernetic Yak Master
11752 Posts |
Posted - 2007-05-03 : 05:31:24
|
| for any kind of recursion use a new feature in Sql Server 2005 called CTE = Common table expressions.look it up in BOL._______________________________________________Causing trouble since 1980blog: http://weblogs.sqlteam.com/mladenp |
 |
|
|
|
|
|
|
|