【问题标题】:Get all possible entries SQL Join获取所有可能的条目 SQL Join
【发布时间】:2020-02-08 01:47:57
【问题描述】:

鉴于以下产品和替代表,我如何才能获得具有所有可能性的输出?

产品表

> 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 函数可能对我有帮助,但我无法构建查询。

【问题讨论】:

  • 您正在尝试绘制图表。要获得第一行,您需要一个连接,但第二行需要 two 连接*。 COALESCE 在这里无济于事。您也许可以使用 [recursive CTE](mssqltips.com/sqlservertip/1520/…)

标签: sql tsql join


【解决方案1】:

简单的连接不能产生这种结果。您需要遍历一个转换图来生成每个查询。您可以使用a CTE 进行递归查询

鉴于这些表格:

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

第一个查询通过连接ProductSubstitution 生成第一个结果。 next 查询通过将前一个 ProductTo 连接到下一个 ProductFrom 来将任何先前的结果与下一个替换连接起来

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2013-05-09
    • 2018-01-06
    • 1970-01-01
    • 2016-02-11
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多