我有两张桌子玩家(姓名,姓氏,目标,团队ID)和团队(姓名,团队ID)。
在下面的查询中,我得到每支队伍的平均进球数,并选择目标数量大于平均数的球员。
SELECT Players.Name, Players.Surname, Teams.Name, Players.Goals, (SELECT ROUND(AVG(Players.Goals)) FROM Players GROUP BY Players.TeamID) AS TeamAverage
FROM Players
JOIN Teams ON Players.TeamID = Teams.TeamID
WHERE Players.Goals > (SELECT ROUND(AVG(Players.Goals))
FROM Players
GROUP BY Players.TeamID)
在 TeamAverage 列中,我想显示每个团队的平均目标数量,但查询只会获得第一个团队的平均目标数量。
我可以迭代这个选择
(SELECT ROUND(AVG(Players.Goals)) FROM Players GROUP BY Players.TeamID)
根据球队的ID获得每个结果?
答案 0 :(得分:2)
通过在括号中使用查询,您创建的子查询首先被评估,并且独立于每行中的行。如果这不是视图和需要作为数据集合或可视化的一部分运行的查询的一部分,那么临时表本身或在存储过程中可以正常工作。如果它需要在视图中,那么使用连接到子查询将起作用。
使用临时表:
SELECT Players.TeamID as TeamID
,ROUND(AVG(Players.Goals)) as PlayerAverage
INTO #temp
FROM Players
Group BY Players.TeamID
SELECT tea.Players.Name
,tea.Players.Surname
,tea.Teams.Name
,tea.Players.Goals
,t.PlayerAverage
FROM Players
JOIN Teams tea ON Players.TeamID = Teams.TeamID
left join #temp t on Players.TeamID = t.TeamID
WHERE Players.Goals > t.PlayerAverage
使用连接的子查询:
SELECT tea.Players.Name
,tea.Players.Surname
,tea.Teams.Name
,tea.Players.Goals
,t.PlayerAverage
FROM Players
JOIN Teams tea ON Players.TeamID = Teams.TeamID
left join (SELECT Players.TeamID as TeamID
,ROUND(AVG(Players.Goals)) as PlayerAverage
FROM Players
Group BY Players.TeamID) t on Players.TeamID = t.TeamID
WHERE Players.Goals > t.PlayerAverage
希望这有帮助!
答案 1 :(得分:2)
试试这个,我个人已经走了使用临时表的路线,但这也应该适合你。我为主表提供了P和T的别名,以帮助您的子查询知道要比较的内容:
SELECT
P.Name,
P.Surname,
T.Name,
P.Goals,
(SELECT ROUND(AVG(Players.Goals)) FROM Players WHERE Players.TeamID = P.TeamID) AS TeamAverage
FROM
Players P
JOIN Teams T ON P.TeamID = T.TeamID
WHERE
P.Goals > (SELECT ROUND(AVG(Players.Goals))
FROM Players
WHERE Players.TeamID = P.TeamID)
答案 2 :(得分:1)
你可以使用临时表来帮助存储teamAverage的结果
CREATE TABLE #players (
goals INT,
NAME NVARCHAR(200),
surname NVARCHAR(200),
teamid INT
)
CREATE TABLE #teams (
NAME NVARCHAR(200),
teamid INT
)
INSERT INTO #teams (
NAME,
teamid
)
VALUES
('team1',1),
('team2',2),
('team3',3)
INSERT INTO #players (
goals,
NAME,
surname,
teamid
)
VALUES
(10,'bob','bob',1),
(2,'bob1','bob',1),
(5,'bob2','bob',1),
(1,'bob3','bob',3),
(3,'bob4','bob',3),
(2,'bob5','bob',3),
(1,'bob6','bob',2),
(2,'bob7','bob',2)
--Create temp table to store team average and teamid
SELECT round(avg(p.Goals), 2) AS average,
t.teamid
INTO #TeamAverages
FROM #players p
LEFT JOIN #teams t
ON p.teamid = t.teamid
GROUP BY t.TeamID
--join on above table and compare to team average table
SELECT p.NAME AS playerName,
p.Surname,
t.NAME AS teamName,
p.Goals,
ta.average
FROM #players p
LEFT JOIN #teams t
ON p.TeamID = t.TeamID
LEFT JOIN #TeamAverages ta
ON ta.teamid = t.teamid
WHERE p.Goals > ta.average
DROP TABLE #players
DROP TABLE #TeamAverages
DROP TABLE #teams