如何通过计算其他字段来查找字段?

时间:2014-02-26 03:14:48

标签: sql ms-access

我想找一位去过两家或更多餐馆的女性。

以下是表格。

卡斯特:

Name  | Gender
--------------
sarah | female
Tim   | Male

访问:

Name  | Restaurant
------------------
sarah | Crab City
Tim   | Domino's
sarah | Crab City
sarah | Krusty City
Tim   | Domino's
sarah | Crab City
Tim   | Domino's

我尝试过的所有东西都没有用...... 我正在使用Access来进行quires。

3 个答案:

答案 0 :(得分:1)

SELECT Temp_Table.name AS NameOfPerson 
FROM   (SELECT cust.name, 
               Count(DISTINCT restaurant) AS UniqueRest 
        FROM   visits, 
               cust 
        WHERE  cust.name = visits.name 
               AND cust.gender = 'female' 
        GROUP  BY cust.name) AS Temp_Table 
WHERE  UniqueRest >= 2 

这将为您提供访问过两家或更多餐馆的女性的名字。

答案 1 :(得分:0)

您可以尝试如下所示的内容。它的要点是加入一个子查询,你使用group by /只需要返回> 2访问客户

select name from Cust
      INNER JOIN 
      (    
        SELECT
          Name,
          Restaurant,     
          COUNT(DISTINCT Restaurant) AS UniqueRest
        FROM
          Visits
        GROUP BY Name
        HAVING COUNT(DISTINCT Restaurant) > 2 
      ) visitingcusts ON cust.Name = visitingcusts.Name AND Cust.gender='female'

答案 2 :(得分:0)

试试这个

select c.name, count(*) as no_visited
from cust c inner join visits v on
c.name=v.name 
where
c.gender='female'
group by c.name
having count(*)>1;

fiddle