至少相加X倍SQL

时间:2019-02-25 13:27:01

标签: sql database db2

[SQL]可以说我有一张桌子,上面有这样的人和地方

NAME - PLACE
John | Park
John | Restaurant
John | Market
Bob  | Park
Bob  | Restaurant
Bob  | Market
Bob  | Pub
Bob  | Work
Tom  | Park
Tom  | Cinema
Ray  | Work
Ray  | Pub

而且我想知道哪些人在同一地方成对在一起至少X次,所以预期输出为:

for X = 1:
John
Bob
Tom
Ray

因为:
约翰和鲍勃一起在公园,餐厅和市场
鲍勃和雷在一起在Work和Pub
汤姆和约翰一起在公园

for X = 2:
John
Bob
Ray

因为:
约翰和鲍勃一起在公园,餐厅和市场
鲍勃和雷在一起在Work和Pub

for X = 3:
John
Bob

因为:
约翰和鲍勃一起在公园,餐厅和市场

我不在乎配对,如果他和另一个人在同一地方,我只想将他添加到结果表中。原因是找出最团结的人。

如果可能,最好使用SQL。

在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

对于X = N(在>=之后):

with t(NAME, PLACE) as (values
  ('John', 'Park')
, ('John', 'Restaurant')
, ('John', 'Market')
, ('Bob', 'Park')
, ('Bob', 'Restaurant')
, ('Bob', 'Market')
, ('Bob', 'Pub')
, ('Bob', 'Work')
, ('Tom', 'Park')
, ('Tom', 'Cinema')
, ('Ray', 'Work')
, ('Ray', 'Pub')
)
select distinct a.name
from t a
where exists (
select 1
from t b
where b.NAME<>a.NAME
and (select count(1) from t ta join t tb on ta.place=tb.place and ta.name=a.name and tb.name=b.name)>=N
);

答案 1 :(得分:0)

您可以使用多个联接来执行此操作。对于X = 1,则:

select p.place, t11.person, t21.person
from (select distinct place as place1
      from t
     ) p join
     t t1
     on t1.place = p.place join
     t t2
     on t2.place = p.place and
        t2.person not in (t1.person);

对于X = 2:

select p.place1, p.place2, t1.person, t2.person
from (select distinct t1.place as place1, t2.place as place2
      from t t1 join
           t t2
           on t1.place < t2.place
     ) p join
     t t11
     on t11.place = p.place1 join
     t t21
     on t21.place = p.place1 and
        t21.person not in (t11.person) join
     t t12
     on t12.place = p.place2 and
        t12.person = t11.person join
     t t22
     on t22.place = p.place2 and
        t22.person = t21.person;

使用此方法添加其他位置,每个新位置都有两个联接。

Here是db <>小提琴。