我正在Snowflake中练习子查询(它支持常见的SQL查询)。我卡住了,无法获得想要的结果。
数据
INSERT INTO members (memid, surname, firstname, address, zipcode, telephone, recommendedby, joindate) VALUES
(12, 'Baker', 'Anne', '55 Powdery Street, Boston', 80743, '844-076-5141', 9, '2012-08-10 14:23:22'),
(21, 'Mackenzie', 'Anna', '64 Perkington Lane, Reading', 64577, '(822) 661-2898', 1, '2012-08-26 09:32:05'),
(6, 'Tracy', 'Burton', '3 Tunisia Drive, Boston', 45678, '(822) 354-9973', NULL, '2012-07-15 08:52:55');
我想获取每个成员的姓名,成员ID,推荐人的姓名和推荐人的ID。
我的代码
with recommender as (
select distinct concat(t1.firstname, ' ', t1.surname) recommender
, memid recommender_id
from "EXERCISES"."CD"."MEMBERS" t1
where exists (select surname from "EXERCISES"."CD"."MEMBERS" t2
where t1.memid = t2.recommendedby)
)
, member as (
select
distinct concat(firstname, ' ', surname) as member,
memid,
recommender,
recommender_id
from recommender
left join "EXERCISES"."CD"."MEMBERS" t3 on recommender.recommender_id = t3.recommendedby
) select * from member
order by member;
注意到输出中缺少Burton Tracy,因为她没有任何推荐者。我想将她的数据保留在输出中。我应该如何重写我的代码?
谢谢
答案 0 :(得分:2)
我不太确定为什么要为此使用CTE ...?还是子查询。
获得推荐会员的人只不过是LEFT JOIN:
select
concat(m.firstname, ' ', m.surname) as member,
m.memid member_id,
concat(r.firstname, ' ', r.surname) as recommender
r.memid recommender_id
from
members m
left join members r on r.memid = m.recommendedby