查询以比较2个表结果并过滤掉某些记录

时间:2012-11-09 14:01:57

标签: sql sql-server-2008-r2

我需要执行查询,以便我可以提取某些文档条目号以进行删除。 (SQL Server 2008) 第一个查询给出了表OINV的结果。

SELECT DocEntry AS "DocEntryINV" , Comments, DocTotal
FROM OINV WHERE DocDate BETWEEN '10-27-2012' AND '10-29-2012' AND Comments IS NOT NULL 
ORDER BY DocTotal ASC, Comments

表ORIN中的第二个

SELECT DocEntry AS "DocEntryCN" , Comments, JrnlMemo, DocTotal
FROM ORIN WHERE DocDate BETWEEN '10-27-2012' AND '10-29-2012' AND Comments IS NOT NULL 
ORDER BY DocTotal ASC, Comments

OINV样本结果

DocEntryINV   JrnlMemo   DocTotal
1             kaka-19        500
3             kaka-19        500
5             kaka-19        500
6             kaka-19        500
7             Rob-23         750
9             Rob-23         750
10            Alex-09        1000
11            Olma-08        1150
12            Paul-17        1250 
13            Paul-17        1250
16            Paul-17        1250
17            Rita-99        1300
19            Rita-99        1300

ORIN样本结果

DocEntryCN    Comments    JrnlMemo      DocTotal
67            reverse     kaka-19       500
69            reverse     kaka-19       500
70            reverse     kaka-19       500
71            reverse     kaka-19       500
74            reverse     kaka-19       500
75            reverse     Rob-23        750
77            reverse     Rob-23        750
78            reverse     Rob-23        750
79            reverse     Rob-23        750
84            reverse     Paul-17       1250
86            reverse     Paul-17       1250
87            reverse     Paul-17       1250

对于表OINV,重复项来自销售点软件,该软件将重复的发票推送到ERP数据库表OINV。旨在通过创建信用票据以使发票无效来纠正这种情况的计划效果不佳,有时会创建比发票更多的信用票据。 (发票总数为45,000 +)。有时,在发票重复所需的地方没有创建信用票据。

如何使用两个表创建查询,我可以在ORIN表上反转额外的条目(如果存在)?我需要查询来返回结果 要反转的DocEntryCN编号,例如上述场景的以下结果。

DocEntryCN    Comments    JrnlMemo      DocTotal
67            reverse     kaka-19       500
69            reverse     kaka-19       500
75            reverse     Rob-23        750
77            reverse     Rob-23        750
78            reverse     Rob-23        750
84            reverse     Paul-17       1250
90            reverse     Rita-99       1300

NB。注释存储唯一的发票编号。如果OINV表中的任何两条注释相同,则表示存在重复错误。 ORIN表中的JrnlMemo字段存储OINV发票编号。对于任何发票重复没有。 k,要反转的正确信用票据数量应为k - 1。

1 个答案:

答案 0 :(得分:1)

您应该知道,在ORIN样本中不存在Rita的数据,因此它不能出现在结果中。我希望这可以解决你的问题:

;with a as
(
select row_number() over(partition by JrnlMemo order by DocEntry) rn,
count(*) over (partition by JrnlMemo) cnt
, DocEntry DocEntryCN, Comments, JrnlMemo, DocTotal from @ORIN
FROM ORIN WHERE DocDate BETWEEN '2012-10-27' AND '2012-10-29' AND Comments IS NOT NULL 
), b as
(
select JrnlMemo, count(*)-2 count 
from oinv
WHERE DocDate BETWEEN '2012-10-27' AND '2012-10-29' AND Comments IS NOT NULL 
group by JrnlMemo
)
select a.DocEntryCn, a.Comments, a.JrnlMemo, a.DocTotal
from a join b on a.cnt > a.rn + b.count and a.JrnlMemo = b.JrnlMemo
order by DocEntryCn