How can I easily flatten this Sql Server hierarchy into an inherited inclusive list?

一个人想着一个人 提交于 2019-12-12 04:44:28

问题


I have tables (for simplicity sake) as outlined below:

Category
--------------------
CategoryId (0 for root nodes)
ParentCategoryId

ProductCategory
--------------------
ProductId
CategoryId

I'd like to be able to retrieve a distinct list of all categories and their inherited products (all the way back to category 0). Category 0 should include ALL products, and all other categories should follow down the hierarchy as infinitely deep as it goes.

Example Table Contents:

CategoryId, ParentCategoryId
---------------------
1, 0
2, 0
3, 0
10, 1
20, 2

ProductId, CategoryId
---------------------
1, 10
2, 1
3, 2
4, 20
5, 3

I'd like the output to travel up the heirarchy and tell me every category that a product can fall under. So a desired result would look something like this:

ProductId, CategoryId
---------------------
1, 0
2, 0
3, 0
4, 0
5, 0
1, 1
2, 1
3, 2
4, 2
5, 3
1, 10
4, 20

Is there an easy way to do this in SQL Server 2005?


回答1:


You can do this with a recursive common table expression (cte).

WITH X (ProductId, CategoryId) AS (
    SELECT ProductId, CategoryId FROM #ProductCategory
    UNION ALL
    SELECT X.ProductId, C.ParentCategoryId FROM X
    INNER JOIN #Category C ON X.CategoryId = C.CategoryId
)
SELECT ProductId, CategoryId FROM X ORDER BY CategoryId, ProductId

More information at http://msdn.microsoft.com/en-us/library/ms186243.aspx



来源:https://stackoverflow.com/questions/702584/how-can-i-easily-flatten-this-sql-server-hierarchy-into-an-inherited-inclusive-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!