2

我正在尝试编写一个 Access 查询,该查询将单个表连接两次,然后对每个表的一个字段进行计数。

SELECT Wines.wID, 
       Wines.num, 
       Wines.Brand, 
       Wines.wYear, 
       Wines.Variety, 
       Wines.Score, 
       g.fName, 
       g.lName , 
       Count(DISTINCT Votes.vote1) AS Vote1,  
       Count(DISTINCT Votes_1.vote2) AS Vote2
FROM   ((Wines 
           LEFT JOIN Guests AS g 
              ON Wines.wID = g.wineID) 
           LEFT JOIN Votes 
              ON Wines.num = Votes.vote1) 
           LEFT JOIN Votes AS Votes_1 
              ON Wines.num = Votes_1.vote2
WHERE (((Wines.pID)=2))
GROUP BY Wines.wID, Wines.num, Wines.Brand, 
         Wines.wYear, Wines.Variety, Wines.Score, g.fName, g.lName
ORDER BY Wines.Score DESC , Count(DISTINCT Votes.vote1) DESC;

但是,它不起作用。COUNT(DISTINCT)似乎在 Access 中不起作用。忽略它可以让查询运行,但我没有得到正确的结果。只使用一次就可以了。我似乎无法在 COUNT 语句中编写子查询,而且我不确定还能做什么。

4

1 回答 1

2

如果您在 MS Access、子查询中工作,则可以使用 DCount,或者可以设置计数查询并加入该查询。我不确定重复来自哪里,所以下面的注释说明了一些想法。它没有经过适当的测试。

SELECT Wines.wID, 
   Wines.num, 
   Wines.Brand, 
   Wines.wYear, 
   Wines.Variety, 
   Wines.Score, 
   g.fName, 
   g.lName , 
   DCount("vote1","votes","vote1"=Wines.num) AS Vote1,  
   (SELECT Count(Vote2) FROM 
      (SELECT DISTINCT vote2 
       FROM votes v
       INNER JOIN Wines w ON v.vote2=w.Num
       WHERE w.pID=2 AND w.num=Wines.num)) AS Vote2
FROM   Wines 
           LEFT JOIN Guests AS g 
              ON Wines.wID = g.wineID

WHERE (((Wines.pID)=2))
GROUP BY Wines.wID, Wines.num, Wines.Brand, 
         Wines.wYear, Wines.Variety, Wines.Score, g.fName, g.lName
ORDER BY Wines.Score DESC , vote1 DESC;
于 2012-07-04T09:01:57.183 回答