使用子查询访问SQL JOIN

问题描述 投票:0回答:1

有人可以告诉我如何将该查询转换为可在MS Access中使用吗?

SELECT Shooters.idShooters, Shooters.firstname, Shooters.lastname, JoinedContingent.Count, JoinedShots.Count 
FROM Shooters 
INNER JOIN 
          (SELECT Shooters.idShooters, Count(Contingent.idContingent) AS Count
           FROM Shooters LEFT JOIN Contingent ON Shooters.idShooters = Contingent.fidShooter
           GROUP BY Shooters.idShooters) 
AS JoinedContingent ON JoinedContingent.idShooters = Shooters.idShooters 
INNER JOIN 
          (SELECT Shooters.idShooters, Count(Shots.idShots) AS Count
           FROM Shooters LEFT JOIN Shots ON Shooters.idShooters = Shots.fidShooters
           GROUP BY Shooters.idShooters) 
AS JoinedShots ON JoinedShots.idShooters = Shooters.idShooters;

背景信息:

我想计算表ShooterContingent中每个Shots的外键出现次数。结果应如下所示:

  idShooters  |  firstname  |  lastname  |  Count  | Count
____________________________________________________________
      1            John          Doe          0       10
      2            Jane          Doe          1       20
      .
      .
      .
sql ms-access join subquery access
1个回答
0
投票

我认为这是您想要的:

SELECT s.idShooters, s.firstname, s.lastname,
        NZ(c.Count, 0), NZ(sh.Count, 0)
FROM (Shooters as s LEFT JOIN 
      (SELECT c.fidShooter, Count(*) AS Count
       FROM Contingent as c
       GROUP BY c.fidShooter
      ) as c
      ON s.idShooters = c.fidShooter
     ) LEFT JOIN
     (SELECT sh.fidShooters, Count(*) AS Count
      FROM Shots as sh
      GROUP BY sh.fidShooters 
     ) as sh
     ON s.idShooters = sh.fidShooters;

请注意,我已将外部联接移至outer查询。实际上,子查询中不需要连接,因此不必理会。

© www.soinside.com 2019 - 2024. All rights reserved.