繁体   English   中英

SQL:在特定列上共享多个值的行

[英]SQL: rows that share several values on a specific column

我有一个Visited了 2 列的表:

ID | City

ID是 integer, City是字符串。

请注意,没有一列本身是键——我们可以有相同的 ID 访问多个城市,而同一城市有多个不同的 ID。

给定一个特定的 ID,我想返回表中访问过输入 ID 所访问的至少一半地方的所有 ID(不包括他们自己)

编辑:我们只计算相同的地方。 所以如果 ID 1 访问了城市 a,b,c。 ID 2 访问了 b,c,d。 ID 3 访问了 c,d,e.

那么对于 ID=1 我们只返回 [2],因为在 ID1 访问的三个城市中,ID3 只访问了一个

将访问表与特定id访问过的城市列表进行内联,然后select ids至少有一半的行数按id分组。

with u as
    (select city as visitedBySpecificId from visited where id = *specificId*),
v as
    (select * from visited inner join u on city = visitedBySpecificId where id <> *specificId*)
(select id from v group by id having count(*) >= (select count(*) from u)/2.0)

小提琴

加入他们并比较计数。

 create table suspect_tracking (id int, city varchar(30)) insert into suspect_tracking values (1, 'Brussels'), (1,'London'), (1,'Paris'), (1,'New York'), (1,'Bangkok'), (1, 'Hong Kong'), (1,'Dubai'), (1,'Singapoor'), (1,'Rome'), (1,'Macau'), (1, 'Istanbul'), (1,'Kuala Lumpur'), (1,'Dehli'), (1,'Tokyo'), (1,'Moscow'), (2,'New York'), (2,'Bangkok'), (2, 'Hong Kong'), (2,'Dubai'), (2,'Singapoor'), (2,'Rome'), (2,'Macau'), (2, 'Istanbul'), (2,'Kuala Lumpur'), (3,'Macau'), (3, 'Istanbul'), (3,'Kuala Lumpur'), (3,'Dehli'), (3,'Tokyo'), (3,'Moscow')
 with cte_suspects as ( select id, city from suspect_tracking group by id, city ), cte_prime_suspect as ( select distinct id, city from suspect_tracking where id = 1 ), cte_prime_total as ( select id, count(city) as cities from cte_prime_suspect group by id ) select sus.id from cte_prime_suspect prime join cte_prime_total primetot on primetot.id = prime.id join cte_suspects sus on sus.city = prime.city and sus.id <> prime.id group by prime.id, sus.id, primetot.cities having count(sus.city) >= primetot.cities/2
  | 编号 |  |  -: |  |  2 |

db<> 在这里摆弄

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM