分割字符串后,在两个表之间显示唯一数据

时间:2017-03-12 17:43:13

标签: sql sql-server sql-server-2016

我有2个表,其中包含4列。我想在查询中找到以下内容:

  1. 当两个表的前3列相同时,

  2. 检查第4列并在;

  3. 之间拆分文字
  4. 如果文字是100%相同(不按订单查看)

  5. 然后显示这两个表之间的差异

  6. 表格如下所示:

    表1:

     c1 |c2 | c3| column-text
    ------------------------------
    | a | a | a | hello          |
    ------------------------------
    | a | a | b | text           |
    ------------------------------
    | a | b | a | just;an;example|
    ------------------------------
    | a | b | b | st0ckexchange  |
    ------------------------------
    

    表2:

     c1 |c2 | c3| column-text
    ------------------------------
    | a | a | b | text           |
    ------------------------------
    | a | a | a | everyone;hello |
    ------------------------------
    | a | b | a | example;just;an|
    ------------------------------
    | a | b | b | stackoverflow  |
    ------------------------------
    

    结果将是:

     c1 |c2 | c3| column-text-t1 | column-text-t2
    ----------------------------------------------
    | a | b | b | hello          | everyone;hello|
    ----------------------------------------------
    | a | b | b | st0ckexchange  | stackoverflow |
    ----------------------------------------------
    

    目前我正在使用此查询:

    Select table1.c1, table1.c2, table1.c3, table1.column-text, table2.column-   text
    from table1 
    join table2 on table1.c1 = table2.c1 
                and table1.c2 = table2.c2 
                and table1.c3 = table2.c3
    where table1.column-text <> table2.column-text
    

    但是当列文本中的字符串与;分开并混合时,这并不能解决问题。

    很抱歉,如果问题有点模糊,我在解释问题时遇到了很多麻烦。

1 个答案:

答案 0 :(得分:1)

Declare @Table1 table (c1 varchar(5), c2 varchar(5), c3 varchar(5),[column-text] varchar(50))
Insert Into @Table1 values
('a','a','a','hello'),
('a','a','b','text'),
('a','b','a','just;an;example'),
('a','b','b','st0ckexchange')

Declare @Table2 table (c1 varchar(5), c2 varchar(5), c3 varchar(5),[column-text] varchar(50))
Insert Into @Table2 values
('a','a','b','text'),
('a','a','a','everyone;hello'),
('a','b','a','example;just;an'),
('a','b','b','stackoverflow')


;with cte as (
Select *,Hits = sum(1) over (Partition by C1,C2,C3,Value)
 From (
        Select Src=1,* From @Table1
        Union All
        Select Src=2,* From @Table2
      ) A
 Cross Apply string_split([column-text],';') B
)
Select A.c1 
      ,A.c2
      ,A.c3
      ,[column-text-t1] = (Select max([column-text]) from @Table1 where c1=A.C1 and c2=A.c2 and c3=A.c3)
      ,[column-text-t2] = (Select max([column-text]) from @Table2 where c1=A.C1 and c2=A.c2 and c3=A.c3)
 From  cte A
 Where Hits=1
 Group By A.C1,A.C2,A.C3

<强>返回

c1  c2  c3  column-text-t1  column-text-t2
a   a   a   hello           everyone;hello
a   b   b   st0ckexchange   stackoverflow

http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=46a901223e41f5f837ea866981efed3b