試圖找出如何使用CTE來解決找到相關互換性的問題。快速失控。你可能還能從中得到一些東西。它不應該是效率低下,儘管它的大小,假設我的想法並不完全錯誤。
CTE中的每個查詢都基本上是一個您可以從CTE訪問的臨時視圖。 Preferred,Roots和HasUsage位不依賴於任何其他CTE表,所以如果需要的話,它們甚至可以是視圖。
;WITH Preferred AS (
-- Find leaves (Any PNO which replaces a PNO but is never replaced.)
SELECT PNO1 FROM InterchangeAbility l
LEFT JOIN InterchangeAbility r ON l.PNO1 = r.PNO
WHERE r.PNO IS NULL
)
, Roots AS (
-- Find roots (Any PNO which gets replaced, but never replaces anything.)
SELECT PNO FROM InterchangeAbility l
LEFT JOIN InterchangeAbility R ON l.PNO = r.PNO1
WHERE r.PNO1 IS NULL
)
, HasUsage AS (
-- Count number of records in usage for each PNO in usage (including 0)
-- Ideally this step wouldn't be necessary, but a LEFT JOIN isn't allowed in
-- The recursive part of a CTE. There may be a more efficient way around this step.
SELECT SkuInfo.PNO, COUNT(Usage.PNO) AS num_records
FROM SkuInfo
LEFT JOIN Usage ON SkuInfo.PNO = SkuInfo.Usage
GROUP BY SkuInfo.PNO
)
, TreeHasUsage AS (
-- Traverse from root to leaf, used leaves will have nonzero usage
-- This is a recursive query, The usage of each root will be the base case.
SELECT p.PNO AS root, p.PNO AS curr, hu.num_records
FROM Roots p
INNER JOIN HasUsage hu ON p.PNO = hu.PNO
UNION ALL
-- This is the recursive part of the query, it finds the PNO which replaces
-- the root element (and so on) and does a running total of the usage associated
-- with this tree branch. By the time we get to a leaf any relevant preferred PNOs
-- will have a nonzero num_records.
SELECT tu.root, hu.PNO, tu.num_records + hu.num_records
FROM TreeHasUsage tu
INNER JOIN InterchangeAbility i ON tu.curr = i.PNO1
INNER JOIN HasUsage hu ON i.PNO = hu.PNO
)
, RelevantRoots AS (
-- Important tree nodes are the ones which have a non zero
-- num_records on one or more leaves. Select the roots of those trees.
SELECT DISTINCT hu.root FROM Preferred p
INNER JOIN TreeHasUsage hu WHERE p.PNO1 = hu.curr
WHERE hu.num_records > 0
)
-- Select every record in InterchangeAbility which belongs to one of the
-- just determined relevant roots.
SELECT * FROM InterchangeAbility i
INNER JOIN RelevantRoots rr ON i.PNO = rr.root
我不能想出一個更好的標題,如果有人有一個建議? – willem
你如何確定零件是首選的變體? –
我在原始問題中使用了首選變體,這是本意是成爲繼任變體的同義詞。我已經編輯了這個問題來清除問題 – willem