找出两列之间的差异

2021-09-10 00:00:00 tsql sql-server

我不确定这个问题的标题是什么,但如果你有更好的主意,请随时编辑它.

I wasn't sure what to title this question, but feel free to edit it if you have a better idea.

假设我有如下所示的数据:

Let's say I have data that looks like this:

Column A                         Column B
John, Sally, Cindy               John, Sally, Cindy, Steve
John, Cindy                      John, Sally, Cindy
Sally, Cindy                     Sally, Cindy
Sally, Steve                     John, Sally, Steve

我想做的是找出差异.我想查看 column B 中存在哪些不在 column A 中的内容,以便我有一列如下所示:

What I would like to do is find the differences. I want to see what exists in column B that are not in column A, so that I have a column that looks like this:

Column C
Steve
Sally
''
John

对此有什么建议吗?

编辑 #1:

表格不是这样存储的,表格每个单元格没有多个值;但是,我从 SQL 查询发送报告,任务是显示 列 a 和 b 具有多个这样的值的差异.

The table is not stored like this, the table does not have multiple values per cell; however, I am sending a report from a SQL query and the assignment is to show the differences with columns a and b having multiple values like this.

这是我的 SQL 查询目前在结果中的样子.

This is what my SQL query currently looks like in the results so far.

编辑 #2:

表格中的每个记录/列交叉点没有多个值.为了让最终用户更容易查看报告,我在交集中放置了多个值,在我的 SQL 查询结果中,以便显示存在和不存在的内容.

There are not multiple values per record/column intersection in the table. To make the report easier to view for the end user, I placed multiple values in the intersection, in my SQL Query Results, so show what is there and what is not there.

我正在尝试创建 column C 以显示差异.

I am trying to create column C to show the differences.

编辑 #3:

Column A 来自一个数据源Column B 来自另一个数据源.

Column A comes from one data source Column B comes from another data source.

A 和 B 不是彼此的子集,我只是选取 2 列并尝试以更简单的方式找出差异.

A and B are not subsets of each other, I am simply taking 2 columns and trying to find the differences in an easier way.

推荐答案

不清楚是否要将多个差异聚合到一个分隔单元格中.

Not clear if you want multiple differences aggregated into one delimited cell.

示例

Declare @YourTable table (ColA varchar(150),ColB varchar(150))
Insert Into @YourTable values 
('John, Sally, Cindy','John, Sally, Cindy, Steve'),
('John, Cindy','John, Sally, Cindy'),
('Sally, Cindy','Sally, Cindy'),
('Sally, Steve','John, Sally, 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, Cindy  John, Sally, Cindy, Steve   Steve
John, Cindy         John, Sally, Cindy          Sally
Sally, Cindy        Sally, Cindy    
Sally, Steve        John, Sally, Steve          John

相关文章