2

我正在尝试编写一个查询,该查询将为我提供每个供应商的所有重复发票的详细信息。

我无法使用 group by,因为我需要发票的所有详细信息。到目前为止,这是我尝试过的

 select 
     vendid, InvcNbr as InvcNbr, InvcDate, OrigDocAmt, PayDate,
     dense_RANK() over (partition by vendid order by invcnbr) RN
 from APDoc
 where InvcDate >= '10/01/2013'

不知道如何从这里开始。

vendid   InvcNbr          InvcDate  OrigDoc   Paydate    RN
AAA  1067458361        10/2/2013     0.00   11/1/2013      8
AAA 1067461099         10/2/2013    16.08   11/1/2013      9
AAA 1067461099          10/2/2013   16.08   11/1/2013      9
AAA 1067461101          10/2/2013   16.08   11/1/2013     10
AAA 1067461101          10/2/2013   16.08   11/1/2013     10
AAA 1067461102          10/2/2013   16.08   11/1/2013     11
AAA 1067461102          10/2/2013   16.08   11/1/2013     11
AAA 1067461103          10/2/2013   92.45   11/1/2013     12
AAA 1067461103          10/2/2013   92.45   11/1/2013     12
4

4 回答 4

4

使用Group BywithHaving子句来识别重复项,然后将这些结果连接到外部查询以查看重复项的详细信息。

这是一个如何做到这一点的例子。

SELECT a.vendid,a.InvcNbr as InvcNbr,a.InvcDate,a.OrigDocAmt,a.PayDate
FROM APDoc a
JOIN (
  SELECT vendid, InvcNbr
  FROM APDoc
  WHERE InvcDate >= '10/01/2013'
  GROUP BY vendid,InvcNbr HAVING COUNT(*) > 1
) b ON a.vendid = b.vendid AND a.InvcNbr = b.InvcNbr
于 2013-11-07T21:43:10.803 回答
0

Something like this using Common-Table-Expressions could build the query up as required.

WITH TempCTE AS (SELECT InvcNbr, vendid, ROW_NUMBER() OVER (PARITION
BY vendid, InvcNbr order by invcnbr ) AS RowNum  FROM APDoc),

// Find all combinations of InvcNbr/vendid exist 
TempCTE2 AS  (SELECT InvcNbr, vendid FROM TempCTE WHERE RowNum > 1)

// Get all the combinations of InvcNbr/vendid 
SELECT * FROM TempCTE2
INNER JOIN APDoc ON TempCTE2.InvcNbr = APDoc.InvcNbr 
AND APDoc.vendid = TempCTE2.vendid
于 2013-11-07T21:40:06.953 回答
0

这也有效,可能更容易理解。

select InvcNbr, COUNT(InvcNbr) as [count]
into #temp1 
from #APDoc
group by InvcNbr

select a.vendid, a.InvcNbr, a.InvcDate, a.OrigDoc, a.Paydate, a.RN
from APDoc a, #temp1 b
where a.InvcNbr = b.InvcNbr
and b.[count] = 2
于 2013-11-07T21:48:44.717 回答
0

假设您在表上有一个主键,您可以使用 EXISTS 子句(可能)非常快速地执行此操作

select * from APDoc a1 where exists 
  (
    select 1 from APDoc a2 
    where a1.pk <> a2.pk
    and a1.vendid = a2.vendid and a1.invcnbr = a2.invcnbr
  )
and InvcDate >= '10/01/2013'
order by vendid , invcnbr

这允许查询优化器生成一个不需要聚合的计划,这在具有许多重复项的非常大的表中会很昂贵。

于 2013-11-08T03:19:41.080 回答