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

How do I find all combinations for an unknown number of options for a product?

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

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

table 看起来像这样。

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

理想情况下,我们会 return 使用 SQL 服务器的所有组合。

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

这只是 return 秒

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

您需要递归 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<>fiddle.