如何找到未知数量产品的所有组合?

问题描述 投票:1回答:1

我有一个包含3列的表,分别是Model_Name,Style_Name和Option_Name。如何连接按Model_Name和Style_Name分组的Option_Names的所有可用组合?我想做的是在单独的行中列出具有选项的每种可能组合的产品。

我一直在尝试使用STRING_AGG(Option_Name, ' / ') WITHIN GROUP,但这只是合并了所有Option_Name。

表格将如下所示。

Model_Name  | Style_Name | Option_Name 
7000 Series | Front Door | White
7000 Series | Front Door | Extra Lock 
7000 Series | Front Door | Foam Filler

理想情况下,我们将使用SQL Server返回所有组合。

7000 Series | Front Door | White
7000 Series | Front Door | White / Extra Lock
7000 Series | Front Door | White / Foam Filler
7000 Series | Front Door | White / Extra Lock / Foam Filler
7000 Series | Front Door | Extra Lock
7000 Series | Front Door | Extra Lock / Foam Filler
7000 Series | Front Door | Foam Filler

其他

SELECT Model_Name, Style_Name
  , STRING_AGG(CAST(Option_Name AS VARCHAR(MAX)), ' / ') WITHIN GROUP (ORDER BY Model_Name, Style_Name) Option_Name 
FROM [dbo].[Product_Option_Master]
GROUP BY Model_Name, Style_Name
ORDER BY Model_Name, Style_Name

这只是返回

7000 Series | Front Door | White / Extra Lock / Foam Filler
sql sql-server combinations product options
1个回答
1
投票

您需要递归CTE:

with cte as (
      select model_name, style_name, option_name, convert(varchar(max), option_name) as option_names
      from Product_Option_Master pom
      union all
      select cte.model_name, cte.style_name, pom.option_name,
             convert(varchar(max), concat(cte.option_names, ' / ', pom.option_name))
      from cte join
           Product_Option_Master pom
           on pom.model_name = cte.model_name and
              pom.style_name = cte.style_name and
              pom.option_name > cte.option_name
     )
select *
from cte;

Here是db <>小提琴。

© www.soinside.com 2019 - 2024. All rights reserved.