代码之家  ›  专栏  ›  技术社区  ›  chhenning

根据1-N关系相邻对齐表

  •  1
  • chhenning  · 技术社区  · 6 年前

    我有两张桌子。一个包含所有服务及其值。第二个表将描述哪些服务与哪些服务相关。

    表1:

    |Service|Value|
    ---------------
    | S1    | 1   |
    | S1    | 2   |
    | S2    | 4   |
    | S3    | 5   |
    | S4    | 6   |
    | S4    | 8   |
    | S4    | 7   |
    | S5    | 3   |
    

    |Service|Related|
    |---------------|
    | S1    | S3    |
    | S1    | S4    |
    | S2    | S5    |
    

    因此,我喜欢将服务及其相关服务彼此相邻地对齐。就这样。这些值可以按升序显示。

    |Service|Value(asc)|Related_Service|Value(asc)|
    ----------------------------------------------|
    | S1    | 1        | S3            | 5        |
    | S1    | 2        | S3            | null     |
    | S1    | 1        | S4            | 6        |
    | S1    | 2        | S4            | 7        |
    | S1    | null     | S4            | 8        |
    | S2    | 4        | S5            | 3        |
    

    这在SQL或T-SQL中是可能的吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Lukasz Szozda    6 年前

    SELECT a.*, b.*
    FROM t2
    LEFT JOIN t1 a ON t2.Service = a.Service
    LEFT JOIN t1 b ON t2.Related = b.Service
    ORDER BY a.value, b.value;
    
        2
  •  0
  •   chhenning    6 年前

    这看起来像是我想要的。使用行号()帮助了我!

    if object_id('tempdb..#a', 'U') is not null 
        drop table #a;
    
    select *, row_number() over (partition by Service order by Value) Row_Num into #a from #Service
    
    select 
        isnull(a.service, b.s) Service, 
        a.Value, 
        isnull(b.Service, a.r) Related_Service, 
        b.Value
    from
    (
        select a.Service, Value, Row_Num, b.Service s, b.Related r from #a a right join #Service_Related b on a.Service = b.Service 
    ) a
    full outer join
    (
        select a.Service, Value, Row_Num, b.Service s, b.Related r from #a a right join #Service_Related b on a.Service = b.Related
    ) b
    on a.s = b.s and a.r = b.r and a.Row_Num = b.Row_Num
    order by a.Service, b.Service