找到两列之间的差异,进行澄清

问题描述

question中所述 假设我有如下数据:

Declare @YourTable table (ColA varchar(150),ColB varchar(150))
Insert Into @YourTable values
('John,Sally','John,Sally,Cindy,Steve')

Select A.*,B.*
 From  @YourTable A
 Outer Apply (
               Select Diff=value
                From (
                       Select value=ltrim(rtrim(value)) From string_split(ColA,',')
                       Union All
                       Select value=ltrim(rtrim(value)) From string_split(ColB,')
                     ) B1
                Group By Value
                Having count(*)=1
             ) B

你有

ColA                ColB                        Diff
John,Sally         John,Steve   Cindy
John,Steve   Steve

但是如何获得

ColA                ColB                        Diff
John,Steve   Cindy,Steve

解决方法

一种方法是string_agg(),我将其放入apply子查询中:

Select A.*,B.*
 From  @YourTable A Outer Apply
       (select string_agg(diff,',') as diff
        from (Select Diff=value
              From (Select value=ltrim(rtrim(value)) From string_split(ColA,')
                    Union All
                    Select value=ltrim(rtrim(value)) From string_split(ColB,')
                   ) B1
              Group By Value
              Having count(*)=1
             ) B
       ) B;

但是我认为使用full join更简单:

select A.*,B.*
from @YourTable A outer apply
     (select string_agg(coalesce(trim(a.value),trim(b.value)),') as diff
      from string_split(ColA,') a full join
           string_split(ColB,') b
           on trim(a.value) = trim(b.value)
      where a.value is null or b.value is null
     ) b;

Here是db 小提琴。

,

您可以从查询中选择并汇总结果:

select cola,colb,string_agg(diff,') as diffs
from ( <your query> ) q
group by cola,colb;