SQLite - 查明某个客户是否被现有客户推荐

SQLite - Find out if some customer was referred by already existing customer

我需要查明某个客户是否是由现有客户推荐的。 Return 结果格式如下“客户姓氏客户名字”“推荐新客户的客户姓氏名字”

这是我的示例数据:

CREATE TABLE customers (
    customer_id int,
    last_name varchar(50),
    first_name varchar(50),
    referred_by_id varchar(50));
    
INSERT INTO customers (customer_id,last_name,first_name, referred_by_id)
    VALUES (1,'John','White',''),
        (2,'Sarah','Green',''),
        (3,'George','Black',''),
        (4,'Mark','Koon',''),
        (5,'Tom','Gone',''),
        (6,'Ezra','Beck',''),
        (7,'Jan','Wick',2),
        (8,'Petr','Lame',''),
        (9,'Lucy','Can',''),
        (10,'Karl','Opel',1),
        (11,'Ron','Varon',10),
        (12,'Harry','Bond',''),
        (13,'Paul','Kong',''),
        (14,'Shaun','King',3),
        (15,'Elisabeth','Yellow','');
        
CREATE TABLE contacts (
    customer_id int,
    address varchar(255),
    city varchar(255),
    phone_number varchar(20),
    email VARCHAR(255));
    
    
INSERT INTO contacts (customer_id,address,city,phone_number,email)
    VALUES (1,'3525  Fort Street','COLUMBUS','2532326578','JW@email.com'),
        (2,'3924  Cooks Mine Road','Albuquerque','5057657670','SarahG@email.com'),
        (3,'925  College Street','Atlanta','4043278560','Georgie@email.com');

CREATE TABLE orders (
    customer_id int,
    order_id INT,
    item varchar(50),
    order_value DECIMAL(12,2),
    order_currency varchar(3),
    order_date TIMESTAMP);
 
INSERT INTO orders (customer_id,order_id,item,order_value,order_currency,order_date)
    VALUES(1,1,'HDMI cable',3.25,'EUR','2020-01-21 14:50:04'),
        (2,2,'Keyboard','15.99','EUR','2020-01-21 17:50:04'),
        (3,3,'Charger','9.99','EUR','2020-01-22 18:00:07'),
        (3,3,'Charger','9.99','EUR','2020-01-22 18:00:07'),
        (3,4,'Phone','225.89','EUR','2020-01-22 19:10:56'),
        (2,5,'Camera','199.99','EUR','2020-01-23 07:50:44'),
        (1,6,'Speakers','75.50','EUR','2020-01-23 08:40:00'),
        (1,6,'Speakers','75.50','EUR','2020-01-23 08:40:00'),
        (2,7,'Mouse','22.19','EUR','2020-01-23 09:20:59');    

您需要 table customers:

的自联接
SELECT c1.last_name || ' ' || c1.first_name customer_name,
       c2.last_name || ' ' || c2.first_name referred_by
FROM customers c1 INNER JOIN customers c2
ON c2.customer_id = c1.referred_by_id

参见demo
结果(对于您发布的样本数据):

> customer_name | referred_by 
> :------------ | :-----------
> Jan Wick      | Sarah Green 
> Karl Opel     | John White  
> Ron Varon     | Karl Opel   
> Shaun King    | George Black