简体   繁体   English

如何比较行中SQL的差异

[英]How to compare rows for differences in SQL

I have a table with DocNum, DocVer, ClientNum, MatterNum. 我有一个带有DocNum,DocVer,ClientNum,MatterNum的表。 Some docs have versions with different ClientNum/MatterNum combinations and I need to create a report with that information. 一些文档的版本具有不同的ClientNum / MatterNum组合,我需要使用该信息创建报告。

1 - I've created a table with DocNum, DocVer, ClientNum, MatterNum where the version is > 1 since only docs with more than a single version are possibly affected. 1-我用DocNum,DocVer,ClientNum,MatterNum创建了一个表,该表的版本> 1,因为只有多于一个版本的文档可能会受到影响。

2 - I'm trying to figure out how best to compare all versions 2+ to the version 1 for a specific doc and denote what doesn't match. 2-我试图找出如何最好地比较特定文档的所有2+版本与1版本,并指出不匹配的地方。 (Group By DocNum, ClientNum, MatterNum, or Join, Etc.) (按DocNum,ClientNum,MatterNum或Join等分组)

I would like a NULL to denote any version 2+ that don't match the ClientNum and MatterNum of the first version. 我想要一个NULL来表示任何与第一个版本的ClientNum和MatterNum不匹配的2+版本。

Sample Table Data: 样本表数据:

docnum, version, client, matter    
351,    1,       15000,  00010    
351,    2,       15000,  00020

The desired output would be a column that denotes docnums and versions that do not match the version 1. 所需的输出将是一列,该列表示文档编号和版本与版本1不匹配。

docnum, version, client, matter, matched 

351,    1,       15000,  00010, y  

351,    2,       15000,  00020, n

You can join your new table that has only version 2+ records back to the original table's version 1 record. 您可以将仅具有版本2+记录的新表加入到原始表的版本1记录中。 Using case you can check if they match and display null if they don't. case您可以检查它们是否匹配,如果不匹配,则显示null。

SELECT 
    yt.DocNum
  , yt.DocVer
  , CASE WHEN yt.ClientNum <> ot.ClientNum THEN NULL ELSE yt.ClientNum END AS 'ClientNum'
  , CASE WHEN yt.NatterNum <> ot.MatterNum THEN NULL ELSE yt.MatterNum END AS 'MatterNum'
FROM YourTable yt -- table with versions 2+
JOIN OriginalTable ot 
  ON yt.DocNum = ot.DocuNum AND ot.DocVer = 1

You could use a self join based on the version number and test the matter column for a change in value, You'll get the idea: 您可以使用基于版本号的自连接并测试问题列中值的变化,您将了解:

 declare @test table (docnum int, version int, client nvarchar(10), matter nvarchar(10));
 insert into @test
 values
 (351, 1, '15000', '00010'),
 (351, 2, '15000', '00020')

 -- assumes your version increases sequentially
 select t1.docnum, t1.matter, t2.matter, case when t1.matter <> t2.matter then 'flag' else 'ok' end [flag]
 from @test t1
 left join @test t2
 on t1.client = t2.client
 and t1.docnum = t2.docnum
 and t1.version = t2.version - 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM