仅从LEFT JOIN的左侧计算记录

时间:2017-10-20 00:05:47

标签: sql ms-access join count left-join

我使用LEFT JOIN构建一个Access查询,其中包括JOIN左表中存在的唯一sampleID的数量,并计算存在于此中的标本(错误)的总数。对于给定的一组样本(TripID),JOIN的右表。这是SQL代码的相关部分:

SELECT DISTINCT t1.TripID, COUNT(t1.SampleID) AS Samples, SUM(t2.C1 + t2.C2) 
AS Bugs FROM tbl_Sample AS t1
LEFT JOIN tbl_Bugs AS t2 ON t1.SampleID = t2.SampleID
GROUP BY t1.TripID

我遇到的麻烦是COUNT(t1.SampleID)没有给我我想要的结果。我想要的结果是给定TripID中t1中存在的唯一SampleID的数量(假设7)。相反,我得到的似乎是t2中的行数,SampleID包含在给定的TripID组中(让我们说77)。如何更改此SQL查询以获取所需的数字(7,而不是77)?

3 个答案:

答案 0 :(得分:0)

这是一个棘手的查询,因为您有不同的层次结构。这是一种方法:

select s.tripid, count(*) as numsamples,
       (select sum(b2.c1 + b2.c2)
        from bugs b join
             tbl_sample s2
             on s2.sampleid = b.sampleid
        where s2.tripid = s.tripid
       ) as numbugs
from tbl_sample s
group by s.tripid

答案 1 :(得分:0)

首先在t2上取总和,然后像这样加入t2:

SELECT t1.TripID, COUNT(t1.SampleID) AS Samples, SUM(t3.Bugs) as Bugs
FROM tbl_Sample AS t1
LEFT Join (
  SELECT t2.SampleID, SUM(t2.C1 + t2.C2) as Bugs
  FROM tbl_Bugs as t2
  GROUP BY SampleID) AS t3 ON t1.SampleID = t3.SampleID
GROUP BY t1.TripID

答案 2 :(得分:0)

你包含了一个带有Group By的DISTINCT。这将删除重复两次,这是不必要的复杂。你可以摆脱DISTINCT。

我将计数与小组中的内容分开。

SELECT dT.TripID
      ,(SELECT COUNT(DISTINCT(SampleID))
          FROM Bugs B
         WHERE B.TripID = dT.TripID
       ) AS [Samples]
      ,dT.Bugs
  FROM (
        SELECT t1.TripID
              ,SUM(t2.C1 + t2.C2) AS Bugs 
          FROM tbl_Sample AS t1 
               LEFT JOIN tbl_Bugs AS t2 ON t1.SampleID = t2.SampleID
         GROUP BY t1.TripID
       ) AS dT