选择MAX值并进行投射

时间:2016-03-27 12:30:19

标签: sql tsql casting max

我有一个包含以下列的表:

[Id]
[fk_Player_Id]
[fk_Innings_Id]
[Minutes]
[Balls]
[Runs]
[fk_HowOut_Id]
[fk_Bowler_Id]

我需要一个返回最大运行记录的查询,但是根据行的fk_HowOut_Id值,我可能需要在该值中添加一个星号。

我试过这个查询 -

SELECT Player.LastName + ' ' + LEFT(player.FirstName, 1) as PlayerName,COUNT(DISTINCT match.MatchId) AS Matches, 
COUNT(CASE WHEN BatInnings.fk_HowOut_Id != 1 THEN 1 ELSE NULL END) AS 'Innings',
COUNT(CASE WHEN BatInnings.fk_HowOut_Id = 7 THEN 1 ELSE NULL END) AS 'Not Outs',
SUM(BatInnings.Runs) AS 'Aggregate',
CASE WHEN (COUNT(CASE WHEN BatInnings.fk_HowOut_Id != 1 THEN 1 ELSE NULL END) - COUNT(CASE WHEN BatInnings.fk_HowOut_Id = 7 THEN 1 ELSE NULL END)) > 0 THEN SUM(BatInnings.Runs) / (COUNT(CASE WHEN BatInnings.fk_HowOut_Id != 1 THEN 1 ELSE NULL END) - COUNT(CASE WHEN BatInnings.fk_HowOut_Id = 7 THEN 1 ELSE NULL END)) ELSE 0 END AS 'Average',
CAST(MAX(BatInnings.Runs) AS varchar(3)) + CASE WHEN BatInnings.fk_HowOut_Id = 7 THEN '*' 
                                                                                 ELSE ''
                                                                                 END AS 'High Score'
FROM Match
JOIN Innings ON Innings.fk_Match_Id = Match.MatchId
JOIN BatInnings ON BatInnings.fk_Innings_Id = Innings.Id
Join Player On player.Id = BatInnings.fk_Player_Id
WHERE Player.ClubId = 1088
group by Player.id, player.FirstName, player.LastName
Order by PlayerName

我收到一条错误消息:

Column 'BatInnings.fk_HowOut_Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我能否指出正确的方向。

谢谢..

2 个答案:

答案 0 :(得分:1)

在查询的上下文中,我认为您在选择的最后一项中的on语句周围忘记了count()。这使得它超出了select中的聚合函数,这会导致你看到的错误:

case

答案 1 :(得分:0)

我有查询使用此查询

(Select CAST(t.Runs as varchar(3)) + CASE WHEN t.fk_HowOut_Id = 7 Then '*' ELSE '' End FROM (SELECT TOP 1 * FROM BatInnings b WHERE b.fk_Player_Id = P.Id Order By b.Runs DESC) t) AS 'High Score'