我的表格格式为:
City Amount Name
New York 10,000 Joe
Boston 10,000 Tom
New York 15,000 Jev
我正在寻找一个查询,该查询将返回至少有25个共同城市的成对的人的名字以及共同城市的确切数目。我的输出需要采用以下形式:
城市,名称1,名称2,计数(*)
我尝试了以下各种变形:
select t1.city, t1.name, t2.name, count(*) from T t1 join T t2
on t1.city = t2.city
where count(*) > 25
但是我没有运气。请指教。
您很近。您需要一个GROUP BY
和HAVING
:
select t1.city, t1.name, t2.name, count(*)
from T t1 join
T t2
on t1.city = t2.city
group by t1.city, t1.name, t2.name
having count(*) > 25;
我相信您可以使用窗口函数来获得想要的东西:
SELECT city, name1, name2, count_of_cities
(
select t1.city, t1.name as Name1, t2.name as Name2, count(*) OVER (PARTITION BY t1.name, t2.name) as count_of_cities
from T t1 join T t2
on t1.city = t2.city
) dt
WHERE dt.count_of_cities > 25;