我有一张桌子:帐户
+-----------+-----------------+------+
| AccountNo | ParentAccountNo | name |
+-----------+-----------------+------+
| 1 | null | ABC |
| 2 | 1 | ABCD |
| 3 | 1 | CDE |
| 4 | 2 | DEF |
| 5 | null | GHI |
| 6 | 3 | MNO |
| 7 | 5 | JKL |
+-----------+-----------------+------+
我需要获得AccountNo
中不存在ParentAccountNo
的结果。
例如,根据上述数据,我期望的结果是:
+-----------+-----------------+------+
| AccountNo | ParentAccountNo | name |
+-----------+-----------------+------+
| 4 | 2 | DEF |
| 6 | 3 | MNO |
| 7 | 5 | JKL |
+-----------+-----------------+------+
接受MySQL
或SQL-Server
的答案。
答案 0 :(得分:4)
通过LEFT JOIN
= AccountNo
上的ParentAccountNo
将表格与自身相关联,您可以过滤掉没有匹配ID
&#39的行; S
WITH Accounts AS(
SELECT *
FROM (VALUES (1,null,'ABC'),
(2,1,'ABCD'),
(3,1,'CDE'),
(4,2,'DEF'),
(5,null,'GHI'),
(6,3,'MNO'),
(7,5,'JKL')) V(AccountNo,ParentAccountNo,name))
SELECT t1.*
FROM Accounts t1
LEFT JOIN Accounts t2 ON t1.AccountNo = t2.ParentAccountNo
WHERE t2.AccountNo IS NULL
您对WITH
的使用感到好奇。 。
这相当于我对WITH
的简写用法:
CREATE TABLE Accounts (
AccountNo INT NOT NULL,
ParentAccountNo INT NULL,
Name VARCHAR(200))
INSERT INTO Accounts
SELECT *
FROM (VALUES (1,null,'ABC'),
(2,1,'ABCD'),
(3,1,'CDE'),
(4,2,'DEF'),
(5,null,'GHI'),
(6,3,'MNO'),
(7,5,'JKL')) V(AccountNo,ParentAccountNo,name)