​数仓经典面试互相关注sql题

2022-06-01 08:43:53 浏览数 (1)

t1表: 代表着uid给to_uid 送了礼物,字段如下:

uid,to_uid

a,b

a,c

b,c

t2表:代表uid的关注者follow_uid,字段如下:

uid,follow_uid

a,b

b,c

求输出:

uid,to_uid,relation

说明:

用户uid给用户to_uid刷了礼物,求用户uid与用户to_uid的互相关注类型relation,

0代表两者互不关注,

1代表用户uid关注了用户to_uid,

2代表用户to_uid关注了用户uid,

3代表互相关注。

Solution

代码语言:javascript复制
SELECT uid,
     to_uid,
     sum(relation) relation
FROM (
-- to_uid关注了uid
SELECT
  t1.uid,
  t1.to_uid,
  CASE WHEN t2.uid IS NULL THEN 0 ELSE 2 END AS relation
FROM t1
LEFT JOIN t2
ON t1.uid = t2.uid
AND t1.to_uid = t2.follow_uid

UNION ALL

-- uid关注了to_uid
SELECT
  t1.uid,
  t1.to_uid,
  CASE WHEN t2.uid IS NULL THEN 0 ELSE 1 END AS relation
FROM t1
LEFT JOIN t2
ON t1.uid = t2.follow_uid
AND t1.to_uid = t2.uid
) t
GROUP BY uid,to_uid;

0 人点赞