我遇到错误:
选择列表中的“ people.playerID”列无效,因为它是 既不包含在汇总函数中,也不包含
select
p.playerid,NameGiven + ' ( ' + namefirst + ' ) ' + nameLast as [Full Name],
teamid, myr,yearid, format(AVG(salary),'C') as [Player Average Salary]
from
Salaries s,
people p ,
(select playerid ,max(yearid) as myr
from Salaries
group by playerID) m
where
s.playerID=p.playerID and
m.playerID=s.playerID
答案 0 :(得分:1)
首先,请避免使用旧的联接表样式。使用ANSI
JOIN
样式
对于您的错误,基本上所有未聚合的列都必须出现在GROUP BY
子句中。就您的情况而言,您错过了整个GROUP BY
select
p.playerid,
NameGiven + ' ( ' + namefirst + ' ) ' + nameLast as [Full Name],
teamid,
myr,
yearid,
format(AVG(salary),'C') as [Player Average Salary]
from Salaries s
inner join people p on s.playerID = p.playerID
inner join (
select playerid ,max(yearid) as myr
from Salaries
group by playerID
) m on m.playerID = s.playerID
group by
p.playerid,
NameGiven + ' ( ' + namefirst + ' ) ' + nameLast,
teamid,
myr,
yearid
答案 1 :(得分:1)
您使用的是旧的join
,这不好join
。我建议您不要使用它。在此处阅读Bad Habits to kick : Using Old Style Joins
select
p.playerid,NameGiven + ' ( ' + namefirst + ' ) ' + nameLast as [Full Name],
teamid, myr,yearid, format(AVG(salary),'C') as [Player Average Salary]
from
Salaries s
Inner Join People p on s.playerID=p.playerID
Inner Join
(select
playerid ,max(yearid) as myr
from
Salaries
group by
playerID) m on m.playerID=s.playerID
Group By
P.PlayerID, NameGiven + ' ( ' + namefirst + ' ) ' + nameLast,
teamid, myr, yearid
您的错误已清除。只需aggregate
加上完整的表达式即可。
答案 2 :(得分:0)
要显示详细信息并汇总这些详细信息的值,可以使用窗口函数。假设您正在寻找被检查球员的平均工资(就像您对myr
所做的那样),则为:
SELECT
p.playerid,
NameGiven + ' ( ' + namefirst + ' ) ' + nameLast AS [Full Name],
teamid,
MAX(yearid) OVER (PARTITION BY p.playerid) AS myr,
yearid,
AVG(salary) OVER (PARTITION BY p.playerid) AS [Player Average Salary]
FROM Salaries s
INNER JOIN people p ON s.playerID = p.playerID;
格式化应在使用记录的客户端应用程序或报告中完成。