开发者

SQL Server - Getting specific data in a Group By query

开发者 https://www.devze.com 2023-03-05 01:21 出处:网络
I have a SQL stored procedure that totals results for a baseball team. I \'Group By\' the appropriate columns and sum the others that I need to total stats for the selected query. It works fine and gi

I have a SQL stored procedure that totals results for a baseball team. I 'Group By' the appropriate columns and sum the others that I need to total stats for the selected query. It works fine and gives me the results I want.

The situation I am running in to is in cases where one Player can belong to different teams within the same season, I cannot group by the team. What I did was I used a subquery to get the players' current team. Again, works fine. But I will need to get more individual information such as the players current teamID. I cannot combine two columns in the subquery mentioned above. Is it bad practice to run multiple subqueries against the main query? Is there any other way to get specific (or distinct) information from a query when using a Group By?

EDIT Added table schema.

SELECT LS.SeasonName, A.SeasonID, PM.PlayerID, PM.PFirstName, PM.PLastName,
(SELECT     ILT.TeamName
                        FROM          League_T AS ILT INNER JOIN
                                               Season_T AS IST ON ILT.TeamID = IST.TeamID INNER JOIN
                                               Season_P AS ISP ON IST.SeasonTeamID = ISP.Season_TeamID
                        WHERE      (ISP.PlayerID = PM.PlayerID) AND (ISP.IsCurrent = 1)) AS 'CurrentTM', 
                       (SELECT     ILT.TeamID
                        FROM          League_Team AS ILT INNER JOIN
                                               Season_Team AS IST ON ILT.TeamID = IST.TeamID INNER JOIN
                                               Season_P AS ISP ON IST.SeasonTeamID = ISP.Season_TeamID
                        WHERE      (ISP.PlayerID = PM.PlayerID) AND (ISP.IsCurrent = 1)) AS 'CurrentTMID', 
Count(Case WHEN GS = 1 THEN GS END) AS GS, --multiple SUM columns here--
FROM Player_Master PM
INNER JOIN Season_P ON PM.PlayerID = Season_P.PlayerID 
INNER JOIN Season_S AS A 
INNER JOIN Season_SD AS B ON A.GameID = B.GameID
INNER JOIN Season_PP AS C ON B.OutcomeID = C.OutcomeID ON Season_P.Season_PlayerID = C.SeasonPl开发者_运维百科ayerID
INNER JOIN League_Season AS LS ON A.SeasonID = LS.SeasonID
WHERE (B.TeamID = @TeamID) AND (LS.IsCurrent = 1)
Group By LS.SeasonName, A.SeasonID, PM.PlayerID, PM.PFirstName, PM.PLastName


If your query requires correlated subqueries then there's nothing wrong with that... presuming you actually need to do it.

Couldn't you JOIN to the "players" table, then join to the "teams" table based on the "player.current_team" column?

0

精彩评论

暂无评论...
验证码 换一张
取 消