访问SQL查询返回计数字段的错误值

时间:2014-04-10 02:33:59

标签: sql ms-access count ms-access-2010

我尝试进行SQL查询以获取客户的姓名以及c列,其中CountCustomers.[Customer ID] = Referrals.[Referred From]许多行通过Referrals.[Used Our Service] = Truec2

连接到引荐

包含Count的第二列,其中Customers.[Customer ID] = Referrals.[Referred From]表示连接到Referrals.[Valid Referral] = Truec2

的推介的行数

此查询正常但在SELECT Customers.[Customer ID], Customers.[First Name], Customers.[Last Name], Count(r.[Valid Referral]) AS c, Count(rr.[Used Our Service]) AS c2 FROM (Customers INNER JOIN Referrals r ON Customers.[Customer ID] = r.[Referred From] AND (r.[Valid Referral])=True) INNER JOIN Referrals rr ON Customers.[Customer ID] = rr.[Referred From] AND (rr.[Used Our Service])=True WHERE (r.[Valid Referral])=True GROUP BY Customers.[Customer ID], Customers.[First Name], Customers.[Last Name] 列中返回错误的数字。它应为1时返回2.

{{1}}

客户表:

enter image description here

推荐表:

enter image description here

结果表:

enter image description here

1 个答案:

答案 0 :(得分:1)

我建议您不要将同一张桌子加入两次,而是将SUMIif一起使用,如下所示:

SELECT 
Customers.[Customer ID], 
Customers.[First Name], 
Customers.[Last Name], 
SUM(Iif(r.[Valid Referral] = True, 1, 0)) AS c, 
Sum(Iif(r.[Used Our Service] = True, 1, 0)) AS c2
FROM Customers 
INNER JOIN Referrals r ON Customers.[Customer ID] = r.[Referred From] 
WHERE (r.[Valid Referral])=True
GROUP BY Customers.[Customer ID], Customers.[First Name], Customers.[Last Name]