【问题标题】:TSQL for getting a list of all product groups and the products in the groupsTSQL 用于获取所有产品组和组中产品的列表
【发布时间】:2021-10-08 11:12:35
【问题描述】:

从 MS SQL Server 获取所有产品组和组中产品的列表。 一个产品可以存在于多个产品组中。

在我迷路之前我所拥有的:(

With CTE_Products As
(
    Select ProductGroupNo, Name, ParentProductGroupNo
    From [dbo].[ProductGroups]
    Where ParentProductGroupNo = 0

    Union All

    Select t.ProductGroupNo, t.Name, t.ParentProductGroupNo
    From [dbo].[ProductGroups] t
    Inner Join CTE_Products c On c.ProductGroupNo = t.ParentProductGroupNo
)

Select
    ProductGroupNo, ParentProductGroupNo
From
    CTE_Products
ORDER BY
    ProductGroupNo

SQL 表

[产品] - 包含产品的表格
-产品编号 (INT)
-描述(VARCHAR)

ProductNo Description
1 Desc1
2 Desc2
3 Desc3
4 Desc4
5 Desc5

[ProductGroups] - 包含产品组的表,如果 ParentProductGroupNo 为 0,则它是根。
-ProductGroupNo (INT)
-名称 (VARCHAR)
-ParentProductGroupNo (INT)

ProductGroupNo Name ParentProductGroupNo
1 Group1 0
2 Group2 0
3 Group3 1
4 Group4 1
5 Group5 2
6 Group6 3
7 Group7 5

[Products2Groups] - 关联产品和组的表。 1 个产品可以存在于多个组中。
-产品编号 (INT)
-ProductGroupNo (INT)

ProductNo ProductGroupNo
1 3
2 5
2 7
3 2
4 6
4 4
4 7

我正在寻找一个查询(可能是 CTE),它可以为我提供如下所示的结果集:

ProductNo ProductGroup
1 Group1 ***** Group3
2 Group2 ***** Group5
2 Group2 ***** Group5 ***** Group7
3 Group2
4 Group1 ***** Group3 ***** Group6
4 Group1 ***** Group4
4 Group2 ***** Group5 ***** Group7
5

【问题讨论】:

  • “所以我不会在这里发布我的垃圾尝试,因为它们让我无处可去” 不,请这样做;向我们展示您的尝试以及为什么没有成功。

标签: sql sql-server tsql common-table-expression hierarchy


【解决方案1】:

通过这个查询,无论你有多少父级,都可以得到你想要的确切答案:

WITH Hierarchy(ChildId, ChildName, ParentId, Parents)
AS
(
    SELECT [ProductGroupNo] Id, Name, [ParentProductGroupNo] ParentId, CAST('' AS VARCHAR(MAX))
        FROM [dbo].[ProductGroups] AS FirtGeneration
        WHERE [ParentProductGroupNo] = 0   
    UNION ALL
    SELECT NextGeneration.[ProductGroupNo], NextGeneration.Name, Parent.ChildId,
    CAST(CASE WHEN Parent.Parents = ''
        THEN(CAST(Parent.ChildName AS VARCHAR(MAX)) + ' ***** ' + NextGeneration.Name)
        ELSE(Parent.Parents + ' ***** ' + CAST(NextGeneration.Name AS VARCHAR(MAX)))
    END AS VARCHAR(MAX))
        FROM [dbo].[ProductGroups] AS NextGeneration
        INNER JOIN Hierarchy AS Parent ON NextGeneration.[ParentProductGroupNo] = Parent.ChildId    
)
SELECT pg.ProductNo , Case when Len(Parents) = 0 then ChildName else Parents end ProductGroup
    FROM Hierarchy h
    inner join [dbo].[Products2Groups] pg
on pg.ProductGroupNo = h.ChildId
order by pg.ProductNo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多