生成报告,显示两个SQL表之间匹配的id
本文关键字:之间 SQL id 两个 报告 显示 | 更新日期: 2023-09-27 18:05:31
我有一个SQL查询,我正在运行,以插入值从table1到table2只有在表行的id匹配:
UPDATE PT
SET CreditInvoiceAmount = CSV.CreditInvoiceAmount
,CreditInvoiceDate = CSV.CreditInvoiceDate
,CreditInvoiceNumber = CSV.CreditInvoiceNumber
,CreditDeniedDate = CSV.CreditDeniedDate
,CreditDeniedReasonId = CSV.CreditDeniedReasonId
,CreditDeniedNotes = CSV.CreditDeniedNotes
,StatusId = CASE
WHEN CSV.CreditInvoiceDate IS NULL
AND CSV.CreditDeniedDate IS NOT NULL
THEN 7
ELSE 8
END
FROM PermanentTable PT
INNER JOIN TemporaryCsvUpload CSV ON PT.Id = CSV.Id
我想说临时表中大约60%的id将与永久表中的id匹配。我想生成某种报告来显示哪些id匹配,哪些不匹配。我显示信息的格式并不重要(HTML表,excel表,等等)。我不确定如何使用查询来获取该信息,以便显示它。谢谢你的帮助!
要显示所有id,以及它们是在一个表中还是在两个表中,请尝试以下操作:它将返回至少在一个表中的id列表,并带有一个标志,指示它们出现在哪个表中:
Select ISNULL(p.ID, t.ID) as ID
, case when p.ID is not null then 'Y' else 'N' end as InPermanentTable
, case when t.ID is not null then 'Y' else 'N' end as InTemporaryTable
from PermanentTable p
full outer join TemporaryCsvUpload t
on p.ID = t.ID
若要只返回临时表中的id,以及指示它们是否在永久表中的标志,请使用以下命令:
Select t.ID
, case when p.ID is not null then 'Y' else 'N' end as InPermanentTable
from TemporaryCsvUpload t
left join PermanentTable p
on p.ID = t.ID
MERGE
语句将符合您正在寻找的内容。它能够更新那些匹配的,插入那些不匹配的,并向您报告哪些匹配,哪些不匹配。最好将输出记录到另一个表中。
MERGE PermanentTable P --target
USING TemporaryCsvUpload T --source
ON P.Id = T.Id
WHEN MATCHED THEN
UPDATE P
SET CreditInvoiceAmount = T.CreditInvoiceAmount
,CreditInvoiceDate = T.CreditInvoiceDate
,CreditInvoiceNumber = T.CreditInvoiceNumber
,CreditDeniedDate = T.CreditDeniedDate
,CreditDeniedReasonId = T.CreditDeniedReasonId
,CreditDeniedNotes = T.CreditDeniedNotes
,StatusId = CASE
WHEN T.CreditInvoiceDate IS NULL
AND T.CreditDeniedDate IS NOT NULL
THEN 7
ELSE 8
END
WHEN NOT MATCHED THEN
INSERT (P columns go here)
VALUES (T columns go here)
OUTPUT $action, Inserted.Id --Inserted will show both inserted and updated to IDs
, Deleted.Id --Deleted will show IDs that were changed in the UPDATE
因为你只是更新/插入,当动作是UPDATE时,插入和删除的Id将是相同的。
您可以将WHEN NOT MATCHED
更改为将日志记录到一个单独的表中,而不是到PermanentTable中。