获取所有可能的SQL连接条目
给定以下产品和替代表,如何获得具有所有可能性的输出 产品表获取所有可能的SQL连接条目,sql,tsql,join,Sql,Tsql,Join,给定以下产品和替代表,如何获得具有所有可能性的输出 产品表 > Category | Year | Product Code > :--------|------|------------- > Animals | 1998 | A0001 > Sports | 2001 | A0002 替代表 > Product From | Product To > :------------|------------ > A0001 | A0
> Category | Year | Product Code
> :--------|------|-------------
> Animals | 1998 | A0001
> Sports | 2001 | A0002
替代表
> Product From | Product To
> :------------|------------
> A0001 | A0003
> A0002 | A0004
> A0003 | A0005
> A0004 | A0006
> A0006 | A0007
产品A0001替换为A0003,然后A0003替换为A0005
产品A0002替换为A0004,A0004替换为A0006,然后A0006替换为A0007
所需输出为:
> Category | Year | Product From | Product To
> :--------|------|--------------|-----------
> Animals | 1998 | A0001 | A0003
> Animals | 1998 | A0003 | A0005
> Sports | 2001 | A0002 | A0004
> Sports | 2001 | A0004 | A0006
> Sports | 2001 | A0006 | A0007
我认为COALESCE函数可能会对我有所帮助,但我无法构建查询。简单的连接无法生成此结果。您需要遍历一个转换图来生成每个查询。您可以使用递归查询来实现这一点 鉴于这些表格:
declare @product table ( Category nvarchar(30), Year int, ProductCode nvarchar(30))
insert into @product
values
('Animals',1998 ,'A0001'),
('Sports' ,2001,'A0002');
declare @substitusion table (ProductFrom nvarchar(30),ProductTo nvarchar(30));
insert into @substitusion
values
('A0001','A0003'),
('A0002','A0004'),
('A0003','A0005'),
('A0004','A0006'),
('A0006','A0007');
此查询将遍历转换并生成所需结果:
with x as (
--Create the initial result by joining Product and Substitution
select Category,Year,ProductFrom,ProductTo
from @product p inner join @substitusion s on p.ProductCode=s.ProductFrom
union all
--Join the *previous* result with the next Substitution
select Category,Year,next.ProductFrom,next.ProductTo
from x as previous
inner join @substitusion next on previous.ProductTo=next.ProductFrom
)
select *
from x
order by Category
这将产生:
Category Year ProductFrom ProductTo
Animals 1998 A0001 A0003
Animals 1998 A0003 A0005
Sports 2001 A0002 A0004
Sports 2001 A0004 A0006
Sports 2001 A0006 A0007
第一个查询通过连接
Product
和Substitution
生成第一个结果。下一个查询通过将前一个ProductTo连接到下一个ProductFrom,将任何前一个结果与下一个替换连接起来,您正在尝试遍历一个图。要获得第一行,您需要一个联接,而第二行需要两个联接*<代码>合并在这里没有帮助。您可以使用[recursive CTE]()