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 |
|
honee
Starting Member
5 Posts |
Posted - 2011-05-16 : 14:36:20
|
| hi!i want to take join on two tables with foreign keys,1st table is Comments having fields CommentID,userID(foreign key),AgentID(foreign Key),Description,DateTimeand another table Ratings with fields RatingID,userID(foreign key),AgentID(foreign Key),Rating,DateTimeUser Table is the table having UserID as a primary key which is used as foreign keys in both comment and rating table.and AgentID is the Primary key in Agent Table used as foreign key in bothe comment and ratings tablenow wot i want is to see the comments and rating given by the same user on a same Agent i-e AgentID .i am taking join on Comment and Ratings table based on User ID for e.g i want to see rating and comment of the given same userhere is the query i am usingSELECT c.CommentID, c.UserID, c.PropertyID, c.PropertyType, c.DateTIme, c.Description, c.AgentID, c.visibility, r.RatingID, r.UserID AS Expr1, r.PropertyID AS Expr2, r.DateTime AS Expr3, r.AgentID AS Expr4, r.RatingFROM Comments AS c INNER JOIN Ratings AS r ON c.UserID = r.UserID AND c.AgentID = r.AgentID AND c.AgentID = 4 but the problem is it is taking cross join.i have two comments on a agent and two rating on the same agentID=4 given by the same userID..it displays record like thisCommentID UserID AgentID RAtingID Description Rating62 1 4 68 best 471 1 4 68 hello 462 1 4 8 best 271 1 4 8 hello 2 |
|
|
MIK_2008
Master Smack Fu Yak Hacker
1054 Posts |
Posted - 2011-05-16 : 20:49:49
|
| So how would you like to have the result if not as its appearing. Do you want the query should return one row (rating and comments) per agent? If so, what would be the criteria for returning information? (what should be the desired output as per above displayed output)CheersMIK |
 |
|
|
honee
Starting Member
5 Posts |
Posted - 2011-05-17 : 06:02:21
|
| i want the result like thisactually i have a DateTime Field in both these tables and both rating and comment are posted at the same time so i want the cmment posted by a user on a specific agent on the same time62 1 4 68 best 4 4/22/2011 12:59:54 AM71 1 4 8 hello 4 5/17/2011 2:22:03 PM |
 |
|
|
MIK_2008
Master Smack Fu Yak Hacker
1054 Posts |
Posted - 2011-05-17 : 13:25:07
|
It seems that you want to get the highest rating in case of duplicate? If so may be following is what you are looking after Select Col1,Col2,Col3,...,ColN,MAX(ColX) As RatingFrom Comments CInner Join Ratings R on C.userID=R.userID and C.AgentID=R.AgentIDInner Join Users U On U.UserID=R.UserIDWhere C.AgentID=4Group by Col1,Col2,Col3,...,ColNYou will need to replace Col1 to ColN in the Select and Group by clauses with the required ones. CheersMIK |
 |
|
|
|
|
|
|
|