匹配两个表时的 True 或 False Indicator

True or False Indicator when matching two tables

我需要一些帮助,我需要从我的数据库中提取数据,现在我有 FD_Documents table 和 FD_Revision table。

我需要匹配来自两个 table 的 GUID,并且还需要一个大于 2 的修订版,一旦匹配完成,它必须在结果中添加一个新列,QC'ed“ 1" 表示匹配条件,"0" 表示不匹配条件。

我写了下面的但没有给我结果。

select Case when EXISTS (
       SELECT FD_Documents.GUID,
      FD_Documents.FD_C231FD9A as [Store],
      FD_Documents.FD_97CDB35A as [Store 2],
      FD_Documents.FD_8B9BD5C6 as [Transaction Date],
      FD_Documents.FD_84A4EF1A as [Account Number],
      FD_Documents.FD_1A3D602F as [Name],
      FD_Documents.FD_F8EFD019 as [Date of Birth],
      FD_Documents.FD_9DAADEC8 as [Document Type],
      FD_Documents.FD_8B43AE0B as [Year],
      FD_Documents.FD_E77BE253 as [File Name]
      FROM FD_Documents, FD_Revisions
      WHERE FD_Documents.GUID = FD_Revisions.GUID
      AND FD_Documents.Deleted = '0'
      AND FD_Revisions.Revision < '3')
      THEN CAST(1 as bit)
      ELSE CAST(0 AS bit) END

我假设 FD_Documents.Deleted 是一个 int 或 bit(不是你的 post 中的字符串),并且 Revision 是一个 int(并且应该大于你问题中的 2描述而不是你的代码),

SELECT FD_Documents.GUID,
  FD_Documents.FD_C231FD9A as [Store],
  FD_Documents.FD_97CDB35A as [Store 2],
  FD_Documents.FD_8B9BD5C6 as [Transaction Date],
  FD_Documents.FD_84A4EF1A as [Account Number],
  FD_Documents.FD_1A3D602F as [Name],
  FD_Documents.FD_F8EFD019 as [Date of Birth],
  FD_Documents.FD_9DAADEC8 as [Document Type],
  FD_Documents.FD_8B43AE0B as [Year],
  FD_Documents.FD_E77BE253 as [File Name],
  CASE ISNULL(FD_Revisions.GUID,'') WHEN '' THEN 0 ELSE 1 END AS IsMatching
  FROM FD_Documents LEFT JOIN FD_Revisions
  ON FD_Documents.GUID = FD_Revisions.GUID
  AND FD_Documents.Deleted = 0
  AND FD_Revisions.Revision > 2

这将为您提供具有所需状态的独特 GUID 列表

select f.GUID from FD_Documents f
inner join FD_Revisions r on f.GUID = r.GUID
where f.Deleted = '0' and r.Revision>2
group by f.GUID

像这样

  SELECT FD_Documents.GUID,
      FD_Documents.FD_C231FD9A as [Store],
      FD_Documents.FD_97CDB35A as [Store 2],
      FD_Documents.FD_8B9BD5C6 as [Transaction Date],
      FD_Documents.FD_84A4EF1A as [Account Number],
      FD_Documents.FD_1A3D602F as [Name],
      FD_Documents.FD_F8EFD019 as [Date of Birth],
      FD_Documents.FD_9DAADEC8 as [Document Type],
      FD_Documents.FD_8B43AE0B as [Year],
      FD_Documents.FD_E77BE253 as [File Name],
  case when r.GUID IS NULL then 1 else 0 end [MatchCount]
  FROM FD_Documents d
        LEFT JOIN  FD_Revisions r on d.GUID = r.GUID AND FD_Revisions.Revision > '2' 
  where FD_Documents.Deleted = '0' 

我不能肯定地说,但这是想法,如果您提供一些测试数据,这个查询可能会更具体,因为这个查询没有经过测试