http://www.sqlfiddle.com/#!3/7a295/1
我在visual studio 10中有一个ms sql数据库,我需要一个查询帮助,从收藏夹表中获取最想要的游戏以及游戏表中的游戏cover_img。我有查询使用第一部分: -
SELECT game_name,
game_platform,
Count(game_name) AS Expr1
FROM favourites
GROUP BY game_name,
game_platform
HAVING ( Count(game_name) = (SELECT Max(mycount) AS Expr1
FROM (SELECT game_name,
Count(game_name) AS mycount
FROM favourites AS Favourites_1
GROUP BY game_name) AS derivedtbl_1) );
但是我无法让cover_img与游戏桌上的最大游戏相匹配,有人可以帮助我,这是我到目前为止所做的,但它不起作用: -
SELECT favourites.game_name,
favourites.game_platform,
games.cover_img,
Count(favourites.game_name) AS Expr1
FROM games
inner join favourites
ON games.name = favourites.game_name
GROUP BY favourites.game_name,
favourites.game_platform,
games.cover_img HAVING (Count(favourites.game_name) = (SELECT
Max(mycount) AS Expr1
FROM
(SELECT game_name,
Count(game_name) AS mycount
FROM favourites AS Favourites_1
GROUP BY game_name) AS derivedtbl_1));
答案 0 :(得分:2)
您可以将问题分成较小的部分:
;
WITH Games AS
(
SELECT *
FROM ( VALUES
('Pacman', 'Atari', 'A'),
('Enduro', 'Atari', 'B'),
('River Raid', 'Atari', 'C')
) AS X (Name, [Platform], cover_img)
), Favourites AS
(
SELECT *
FROM ( VALUES
('Pacman', 'Atari'),
('Pacman', 'Atari'),
('Pacman', 'Atari'),
('Enduro', 'Atari')
) AS Y (game_name, game_platform)
), MostWanted AS
( -- Identify the most wanted game, per platform
SELECT game_name, game_platform, COUNT(*) Total,
ROW_NUMBER() OVER
(
PARTITION BY /*game_name,*/ game_platform
ORDER BY COUNT(*) DESC
) [Order]
FROM Favourites
GROUP BY game_name, game_platform
)
SELECT MostWanted.*, Games.cover_img
FROM MostWanted
JOIN Games -- JOIN that with games table to get more details
ON MostWanted.game_name = Games.Name
WHERE MostWanted.[Order] = 1 -- Only the first most wanted
答案 1 :(得分:1)
您的第一个查询将选择您要查找的游戏。
SELECT game_name,
game_platform,
Count(game_name) AS Expr1
FROM favourites
GROUP BY game_name,
game_platform
HAVING ( Count(game_name) = (SELECT Max(mycount) AS Expr1
FROM (SELECT game_name,
Count(game_name) AS mycount
FROM favourites AS Favourites_1
GROUP BY game_name) AS derivedtbl_1) );
现在你需要的是一个包装器查询来查找与这些游戏相关的所有图像。
SELECT xx.game_name,xx.game_platform, games.cover_img
from
(SELECT game_name,
game_platform
FROM favourites
GROUP BY game_name,
game_platform
HAVING ( Count(game_name) = (SELECT Max(mycount) AS Expr1
FROM (SELECT game_name,
Count(game_name) AS mycount
FROM favourites AS Favourites_1
GROUP BY game_name) AS derivedtbl_1
)
)
) xx
join games on games.game_name=xx.game_name
and games.game_platform=xx.game_platform
试一试。
答案 2 :(得分:1)
这样做你想要的吗?
SELECT TOP 1 f.game_name, f.game_platform, g.cover_img,
Count(f.game_name) as cnt
FROM games g inner join
favourites f
ON g.name = f.game_name
GROUP BY f.game_name, f.game_platform, g.cover_img
ORDER BY Count(f.game_name) desc;