2012-07-04 82 views
2

我想寫一個連接兩個單一表的Access查詢,然後在每個字段上運行一個計數。COUNT()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語句中編寫子查詢,我也不確定還有什麼要做。

回答

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;