排列组合问题【通过join不等式】
这种问题,就是数学的排列不等式,一个队伍只能和其余队伍比一次,不能重复
方法1:可以直接通过join,最后on是一个不等式【排列组合问题的解决方式】
方法2:也可以是提前多加一列,加上一个序号
方法1
sql
select
t1.team_name team_name_2,
t2.team_name team_name_1
from
(
select
team_name,
case
when team_name='湖人' then 2
when team_name='骑士' then 4
when team_name='勇士' then 1
else 3 end flag
from team
) t1
join
(
select
team_name,
case
when team_name='湖人' then 2
when team_name='骑士' then 4
when team_name='勇士' then 1
else 3 end flag
from team
) t2
on t1.flag > t2.flag
方法2
sql
select
team_name team_name_1,
team_name_2
from
team
join(
select team_name team_name_2
from team
)t1
on team_name < team_name_2
另外的思路:
也还有种思路,我就是想这样,不过没成功,就是通过炸裂函数+开窗
-- 思路:
-- 通过理解题意 明白了每个队伍只比一次其实就是一个数学的关联问题
-- 所以就想到了使用开窗函数和高级聚合函数和炸裂函数
-- 先通过高级聚合函数 开窗 将当前行的值到最后一行的队伍名封装到一个集合中
-- 然后将集合再炸裂开 并将两个队伍名字相同的行过滤掉即可得出想要的结果
sql
SELECT
t2.team_name team_name_1,
t2.team_name2 team_name_2
FROM (
SELECT
t1.team_name,
team_name2
FROM
( SELECT
team_name,
collect_list(team_name) OVER (ORDER BY team_name ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) name_list
FROM team
) t1
LATERAL VIEW explode(t1.name_list) temp AS team_name2
) t2
WHERE t2.team_name != t2.team_name2