基于计数的加入

问题描述 投票:0回答:2

我的表格格式为:

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

但是我没有运气。请指教。

sql
2个回答
0
投票

您很近。您需要一个GROUP BYHAVING

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;

0
投票

我相信您可以使用窗口函数来获得想要的东西:

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;
© www.soinside.com 2019 - 2024. All rights reserved.