CREATE TABLE "Games"
("ID" int,
"Title" varchar(30),
"Popularity" int)
Here is the second table:
CREATE TABLE "Related"
("ID" int,
"rID" int)
Here is the data for the first table:
INSERT INTO Games (id, title, popularity) VALUES (1, 'Tag Dodgeball', 10)
INSERT INTO Games (id, title, popularity) VALUES (2, 'Freeball', 10)
INSERT INTO Games (id, title, popularity) VALUES (3, 'Doctor Dodgeball', 10)
INSERT INTO Games (id, title, popularity) VALUES (4, 'Kickball', 8)
INSERT INTO Games (id, title, popularity) VALUES (5, 'Fooseball', 8)
INSERT INTO Games (id, title, popularity) VALUES (6, 'Basketball', 7)
INSERT INTO Games (id, title, popularity) VALUES (7, 'Knockout', 6)
Here is the data for the second table:
INSERT INTO Related (ID, rID) VALUES (1,2)
INSERT INTO Related (ID, rID) VALUES (2,1)
INSERT INTO Related (ID, rID) VALUES (1,3)
INSERT INTO Related (ID, rID) VALUES (2,3)
INSERT INTO Related (ID, rID) VALUES (3,1)
INSERT INTO Related (ID, rID) VALUES (3,2)
INSERT INTO Related (ID, rID) VALUES (6,7)
INSERT INTO Related (ID, rID) VALUES (7,6)
Now, lets say a person wants to grab the top three results:
SET ROWCOUNT 3
Select * from Game ORDER BY Popularity
Result Set:
1 Tag Dodgeball 10
2 Freeball 10
3 Dr. Dodgeball 10
But,what if this person doesn't want to play three related games in a row?This is my dilemma. How do I get the following result set:
1 Tag Dodgeball 10
2 Kickball 8
3 Fooseball 8
Therelated table tells which games are related to which, but how do I getthe select statement to realize that it should not select any gamesthat are related once it already has one in the result set?
I can't use distinct, b/c if I do, any games which don't have a relationship are eliminated, as their rID is null.
Pseudo-Code might look something like this:
SET ROWCOUNT 3
Select * from Game ORDER BY Popularity (where ID !=rID)
Please help. I've banging my head against this one for quite some time.
Respectfully,
David.
Cheesy way of doing this, assuming you never get more than 1000 games...
SELECT g.*
FROM Games g
JOIN(SELECT*FROM relatedUNIONSELECT id,idFROM games) rON g.id=r.id
JOIN games g2ON g2.id=r.rid
GROUPBY g.ID,g.title,g.popularity
HAVINGmax(g2.popularity*1000-g2.id)% 1000= 1000-g.id
ORDERBY popularityDESC,ID
If you need more games, you can change the three 1000's to whatever number you need. There's a "better" way, but this was fast and easy.
No comments:
Post a Comment