0

所以这是我原来的查询:

SELECT Batting.playerID, SUM(G) as 'G', SUM(AB) as 'AB', SUM(R) as 'R', SUM(H) as 'H', SUM(Doub) as '2B',  SUM(Trip) as '3B', 
                         SUM(HR) as 'HR', SUM(RBI) as 'RBI', SUM(SB) as 'SB', SUM(CS) as 'CS', SUM(BB) as 'BB', 
                         SUM(SO) as 'SO', SUM(IBB) as 'IBB', SUM(HBP) as 'HBP', SUM(SH) as 'SH', SUM(SF) as 'SF', SUM(GIDP) as 'GIDP', 
                         Master.nameLast, Master.nameFirst, 
    FROM Batting
        JOIN Master ON Batting.playerID = Master.playerID

WHERE Master.nameLast LIKE @lastname + '%' 
GROUP BY Batting.playerID, Master.nameLast, Master.nameFirst

这是我的新查询:

SELECT Batting.playerID, SUM(G) as 'G', SUM(AB) as 'AB', SUM(R) as 'R', SUM(H) as 'H', SUM(Doub) as '2B',  SUM(Trip) as '3B', 
                         SUM(HR) as 'HR', SUM(RBI) as 'RBI', SUM(SB) as 'SB', SUM(CS) as 'CS', SUM(BB) as 'BB', 
                         SUM(SO) as 'SO', SUM(IBB) as 'IBB', SUM(HBP) as 'HBP', SUM(SH) as 'SH', SUM(SF) as 'SF', SUM(GIDP) as 'GIDP', 
                         Master.nameLast, Master.nameFirst, Fielding.POS
    FROM Batting
        JOIN Master ON Batting.playerID = Master.playerID
        JOIN Fielding ON Master.playerID = Fielding.playerID
WHERE Master.nameLast LIKE @lastname + '%' 
AND Fielding.POS IN ('C', '1B','2B','3B', 'SS', 'LF', 'RF', 'CF', 'OF', 'DH')
GROUP BY Batting.playerID, Master.nameLast, Master.nameFirst, Fielding.POS

我所做的只是从字段表中添加 pos 列。现在我必须对击球台上的所有这些列求和才能得到总数。一些结果在与总和相关的字段表上有多个 POS,即,有人在一个 pos 有 50 场比赛,在另一个 pos 有 50 场比赛。我的查询有效,但是在此过程中返回的数字会成倍增加(第二个查询比第一个大得多),并且我根据 pos 获得了多条记录,我只想要一个。有什么想法吗?我尝试了左外连接,但没有做任何事情

4

2 回答 2

0

问题是表中的1条记录Master可以有表中的多条记录,这会导致查询多次Fielding返回表中的每条记录。Batting如果您需要Fielding表中的数据,则需要将其限制为每个 playerID 的单个记录。

于 2013-05-09T15:43:59.153 回答
0

您必须执行 2 个单独的查询并与 UNION ALL 合并以避免行乘法。

  • 之一Batting JOIN Master
  • 另一个在Fielding JOIN Master
于 2013-05-09T15:48:35.013 回答