1

我需要执行一个查询,以便我可以提取某些文档条目号以进行删除。(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

注意。注释存储唯一的发票编号。如果 OINV 表中任意两条注释相同,则表示存在重复错误。ORIN 表中的 JrnlMemo 字段存储 OINV 发票编号。对于任何发票重复没有。k,要冲销的贷方票据的正确数量应该是 k - 1。

4

1 回答 1

1

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

;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
于 2012-11-12T13:02:27.747 回答