我正在研究一個看起來像這樣的多父子層次結構。這是具有 105k 條記錄的表的子集。
| 節點密鑰 | 父鍵 | 孩子 | 家長 |
|---|---|---|---|
| 1 | 一種 | ||
| 2 | 乙 | ||
| 3 | C | 一種 | |
| 4 | D | 乙 | |
| 5 | D | C |
我需要使用具有以下條件的資料填充列 ParentKey。
如果 Parent 中的值為NULL,則在 ParentKeyNULL中也設定該值。
如果Parent中的值是NOT NULL并且也在Child中,則選擇對應的NodeKey并將其設定為ParentKey中的值(見第二表)。
我可以這樣做,但是當 Parent 列中的值在 Child 列中出現不止一次時會出現問題。
在第 5 行,在 3 或 4 之間選擇哪個值無關緊要。它可以是任何一個。
| 節點密鑰 | 父鍵 | 孩子 | 家長 |
|---|---|---|---|
| 1 | 一種 | ||
| 2 | 乙 | ||
| 3 | 1 | C | 一種 |
| 4 | 2 | C | 乙 |
| 5 | 不管是3還是4 | D | C |
SELECT (CASE WHEN Parent IS NULL THEN NULL
ELSE
(SELECT NodeKey from table WHERE Parent IN (SELECT Child from table)) END) as ParentKey
執行此代碼時,它告訴我“子查詢回傳的值大于 1”,這是有道理的。但是,無論在哪里,我把一個max()或min()它不作業。
當我放在max()
NodeKey 前面時,它只回傳一列全是 NULL 和 105314。105314 是表中的行數。
我正在使用 SQL Server Management Studio 17。
uj5u.com熱心網友回復:
如果使用什么 ParentKey 無關緊要,您可以使用 MIN (MAX) 函式:
SELECT
TBL.NodeKey,
PK AS ParentKey,
TBL.Child,
TBL.Parent
FROM TBL
LEFT JOIN (
SELECT Child, MIN(NodeKey) PK FROM TBL GROUP BY Child
) P ON P.Child = TBL.Parent;
測驗 MS SQL 查詢
或其他版本:
SELECT
TBL.NodeKey,
MIN(P.NodeKey) AS ParentKey,
TBL.Child,
TBL.Parent
FROM TBL
LEFT JOIN TBL P ON P.Child = TBL.Parent
GROUP BY TBL.NodeKey, TBL.Child, TBL.Parent;
結果:
========= =========== ======= ========
| NodeKey | ParentKey | Child | Parent |
========= =========== ======= ========
| 1 | (null) | A | (null) |
--------- ----------- ------- --------
| 2 | (null) | B | (null) |
--------- ----------- ------- --------
| 3 | 1 | C | A |
--------- ----------- ------- --------
| 4 | 2 | C | B |
--------- ----------- ------- --------
| 5 | 3 | D | C |
--------- ----------- ------- --------
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365085.html
標籤:sql sql-server 亲子
上一篇:SQL獲取上個月的更改
下一篇:加入遞回表
