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 |
|
jaspreetsingh8
Starting Member
3 Posts |
Posted - 2010-02-27 : 06:21:07
|
| I want a sql queryFollowing is Tags of User1.USER1 :- A,B,C,D,E,FAnd other users like User2, User3, User4, User5 has associated User1 Tags.USER2 :- A,B,C,DUSER3 :- C,D,E,FUSER4 :- A,BUSER5 :- C,E,FCount of A Tag group by User :- 2Count of B Tag group by User :- 2Count of C Tag group by User :- 3Count of D Tag group by User :- 2Count of E Tag group by User :- 2Count of F Tag group by User :- 2Total - 13USER2 - A,B,C,D :- 2 + 2 + 3 + 2 = 9USER3 - C,D,E,F :- 3 + 2 + 2 + 2 = 9USER4 - A,B :- 2 + 2 = 4USER5 - C,E,F :- 3 + 2 + 2 = 7What i want to show the result fetch tags of User1 and other User which are associated with his tags priority wise of users tag sumFinal Result is like as following:USER2 - A,B,C,D :- 2 + 2 + 3 + 2 = 9USER3 - C,D,E,F :- 3 + 2 + 2 + 2 = 9USER5 - C,E,F :- 3 + 2 + 2 = 7USER4 - A,B :- 2 + 2 = 4My tables areTags :- Id, TagNameUserTags :- Id, TagId, UserId, TagTypeUsers :- Id, FirstName, LastNameJaspreet Singh |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-02-27 : 06:41:20
|
| [code]SELECT COALESCE(u1.FirstName + ' ','') + COALESCE(u1.LastName,'') AS User,SUM(t2.TagCount)FROM Users u1JOIN UserTags ut1ON ut1.UserId = u1.rIdJOIN Tags t1ON t1.Id = ut1.TagIdJOIN(SELECT t.TagName,COUNT(*) AS TagCountFROM Users uJOIN UserTags utON ut.UserId = u.IdJOIN Tags tON t.Id = ut.TagIdWHERE COALESCE(u.FirstName + ' ','') + COALESCE(u.LastName,'') = 'USER1'GROUP BY t.TagName)t2ON t2.TagName = t1.TagNameWHERE COALESCE(u1.FirstName + ' ','') + COALESCE(u1.LastName,'') <> 'USER1'GROUP BY COALESCE(u1.FirstName + ' ','') + COALESCE(u1.LastName,'')[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-02-27 : 06:49:53
|
or using sql 2005 applySELECT COALESCE(u.FirstName + ' ','') + COALESCE(u.LastName,''),SUM(t.TagCnt) FROM Users uCROSS APPLY(SELECT TagId FROM UserTags WHERE UserId=u.Id )utOUTER APPLY (SELECT COUNT(*) AS TagCnt FROM UserTags ut1 JOIN Users u1 ON u1.Id=ut1.UserId WHERE COALESCE(u1.FirstName + ' ','') + COALESCE(u1.LastName,'') = 'USER1 AND ut1.TagId=ut.TagId )tWHERE COALESCE(u.FirstName + ' ','') + COALESCE(u.LastName,'') <> 'USER1'GROUP BY COALESCE(u.FirstName + ' ','') + COALESCE(u.LastName,'') ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
|
|
|
|
|
|