我有一张表CUST1,里面有数据。每个都有一个唯一的member_ID,如图所示。
现在还有另一个表CUST1_TREE,如图所示。
我想表明谁是孩子的父母。我希望得到的结果是新表,如图所示
我无法嵌入图片,所以请点击链接查看图片。 任何有关上述的帮助将受到高度赞赏。感谢
答案 0 :(得分:0)
下面是一个脚本,根据您的示例构建2个临时表,并按您的请求查询结果。随意提出任何问题。
编辑:我理解你的学习,而事实是我们都在学习。坚持下去!create TABLE #CUST1
(
MEMBER_ID INT,
MEMBER_NAME VARCHAR(10),
MEMBER_D VARCHAR(25)
)
CREATE TABLE #CUST1_TREE
(
MEMBER_ID INT,
MEMBER_PARENT_ID INT
)
INSERT INTO #CUST1
(MEMBER_ID, MEMBER_NAME, MEMBER_D)
VALUES
(10,'N1','EMIL'),
(20,'N2','MARIA'),
(30,'N3','AMIR'),
(1005,'N4','VIVI'),
(2006,'N5','RJ'),
(1007,'N6','EMIL J'),
(2095,'N7','EMILY'),
(1055,'N8','TESSAN'),
(10055,'N9','MIKE')
INSERT INTO #CUST1_TREE
(MEMBER_ID, MEMBER_PARENT_ID)
VALUES
(10, NULL),
(20, NULL),
(30, NULL),
(1005, 20),
(2006, 20),
(1007, 10),
(2095, 10),
(1055, 30),
(10055, 1055)
SELECT
C1.MEMBER_ID,
C1.MEMBER_NAME,
C1.MEMBER_D,
CT1.MEMBER_ID,
C2.MEMBER_NAME,
C2.MEMBER_D,
CT2.MEMBER_ID,
C3.MEMBER_NAME,
C3.MEMBER_D
FROM #CUST1 C1
LEFT JOIN #CUST1_TREE CT1
ON C1.MEMBER_ID = CT1.MEMBER_PARENT_ID
LEFT JOIN #CUST1 C2
ON CT1.MEMBER_ID = C2.MEMBER_ID
LEFT JOIN #CUST1_TREE CT2
ON CT1.MEMBER_ID = CT2.MEMBER_PARENT_ID
LEFT JOIN #CUST1 C3
ON CT2.MEMBER_ID = C3.MEMBER_ID
WHERE CT1.MEMBER_ID IS NOT NULL
希望这有帮助!如果这回答了您的问题,请务必查看此答案。谢谢!