在SQLite数据库中,我有一个表:
ID | ParentID | Price
---------------------
1 | null | -1
2 | 1 | 100
3 | 1 | 200
4 | null | -1
5 | 4 | 300
6 | 4 | 300
如何使用子价格更新父行价格(ParentID为空),并遵循以下规则:
我正在寻找的输出是:
ID | ParentID | Price
---------------------
1 | null | 0
2 | 1 | 100
3 | 1 | 200
4 | null | 300
5 | 4 | 300
6 | 4 | 300
谢谢!
答案 0 :(得分:1)
我找到了答案:
UPDATE
MyTable
SET
Price = (SELECT P.ChildPrice
FROM (SELECT ParentID,
(CASE COUNT(DISTINCT Price)
WHEN 1 THEN Price
ELSE 0 END) AS ChildPrice
FROM InventoryItem
WHERE ParentID IS NOT NULL
GROUP BY ParentID) P
WHERE InventoryItem.ID = P.ParentID)
WHERE
ParentID IS NULL