CustID Name ReferredBy
1 Neeta Sayam
2 Dolly Dilly 1
3 Meena Kimi 2
查找其他人推荐的所有客户的姓名。
输出应该是dolly dilly和meena kimi。
我已经成功地找到了通过查询重新评估其他人的客户
SELECT c1.name FROM Customer c1 JOIN Customer c2 ON c1.custid=c2. ReferredBy
答案 0 :(得分:6)
除非我遗漏了什么:
SELECT *
FROM Customer
WHERE ReferredBy IS NOT NULL
答案 1 :(得分:1)
有很多方法可以实现你想要的,但有一个有趣的是使用CTE,因为它允许你逐级获得引用,例如在你的情况下,零级将是Neeta syam
没有引用,第一级是dolly dilly
和meena kimi
。以下查询将返回dolly dilly
和meena kimi
,它们位于where reference = 1
指定的级别1中,如下所示:
WITH CTEs (Id, CustomerName, Reference, RefCustomer)
AS
(
SELECT
Id,
Name,
0 As Reference,
CONVERT(VARCHAR(length), 'No Reference') AS RefCustomer
FROM Customers
WHERE ReferredBy IS NULL
UNION ALL
SELECT
c.CustId,
c.Name,
cs.Reference + 1,
cs.CustomerName
FROM Customers c
INNER JOIN Ctes cs ON c.ReferedBy = cs.Id
)
SELECT CustomerName, RefCustomer
FROM Ctes
WHERE Reference = 1;