0
id        | person  | cities travelled  | distance

----------+---------+-------------+-----------

1         | jack   | japan              | 8

2         | Joe    | florida            | 11 

3         | Joe    | california         | 215 

4         | Jane   | ghana              | 3

5         | Jane   | florida            | 8

6         | Joe    | jakarta            | 11 

7         | Joe    | california         | 215 

8         | Joe    | japan              | 3

对于两个给定的人“简”和“乔”,我想找到他们旅行过的共同城市。什么是 sql 查询。在这种情况下,我们可以看到简和乔都去过的常见城市是“佛罗里达”。如何在 sql 查询的帮助下找到它?

4

2 回答 2

2

你可以用group byand做到这一点having

select CitiesTravelled
from t
group by CitiesTravelled
having sum(person = 'Joe') > 0 and
       sum(person = 'Jane') > 0;

通过将逻辑放在having子句中,您可以轻松地概括查询。这是 JaneJoe 的版本:

select CitiesTravelled
from t
group by CitiesTravelled
having sum(person = 'Joe') > 0 or
       sum(person = 'Jane') > 0;

这是 Jane、Joe 和 Jack 所旅行城市的版本:

select CitiesTravelled
from t
group by CitiesTravelled
having sum(person = 'Joe') > 0 and
       sum(person = 'Jane') > 0 and
       sum(person = 'Jack') > 0;

编辑:

如果要添加行驶距离,可以将其更改为select

select CitiesTravelled, min(DistanceTravelled)
select CitiesTravelled, avg(DistanceTravelled)
select CitiesTravelled, max(case when person = 'Jane' then DistanceTravelled end)
于 2013-08-22T11:09:29.343 回答
0
select CitiesTravelled 
from t
where person = 'Joe'
and CitiesTravelled in (
   select CitiesTravelled
   from t
   where person = 'Jane'
);

或者

select CitiesTravelled
from t t1
where person = 'Joe'
and exists (
  select t2.CitiesTravelled
  from t t2
  where t2.person = 'Jane'
  and  t2.CitiesTravelled = t1.CitiesTravelled
);
于 2013-08-22T11:25:36.890 回答