我已经用尽了所有可以找到的例子,但我仍然没有得到我需要的结果。
我有一张发票表,我需要找到在多个客户上使用相同发票号的任何实例。发票编号可以在表格中多次出现,每个记录都按发票和发票序号区分,但每个发票只应有一个客户,但有些错误已经悄悄进入。
我需要的是仅报告有两个或更多客户的发票。在下面的数据中,Cust 45001301不应该是Invoice 708,seq 3的客户编号。
Cust No Invoice No Seq No Input Date
700180 708 1 9/30/2007
700180 708 2 9/30/2007
45001301 708 3 9/30/2007
700180 708 4 9/30/2007
700190 709 1 9/30/2007
700190 709 2 9/30/2007
我试图做的只是通过查询获得一个简单的组,只显示那些客户多于此的发票 -
[Invoice No] [Cust no]
708 700180
708 45001301
但我只想看到有两个或更多客户的人,所以在上面的例子中我不会看到发票709的条目,因为它只有一个客户。
[Invoice No] [Cust no]
708 700180
708 45001301
709 700190
答案 0 :(得分:1)
首先创建一个查询,该查询返回[Invoice No]
和[Cust no]
的所有不同组合。然后将其用作子查询,在其中计算每[Invoice No]
个客户的数量,并添加HAVING
子句以将输出限制为仅计数大于1的那些。
SELECT sub.[Invoice No], Count(*) AS customers
FROM
(
SELECT DISTINCT [Invoice No], [Cust no]
FROM Invoices
) AS sub
GROUP BY sub.[Invoice No]
HAVING Count(*) > 1;
如果您需要查看哪些客户的重复发票,INNER JOIN
查询Invoices
表。
SELECT DISTINCT i.[Invoice No], sub2.customers, i.[Cust No]
FROM
Invoices AS i
INNER JOIN
(
SELECT sub.[Invoice No], Count(*) AS customers
FROM
(
SELECT DISTINCT [Invoice No], [Cust no]
FROM Invoices
) AS sub
GROUP BY sub.[Invoice No]
HAVING Count(*) > 1
) AS sub2
ON i.[Invoice No] = sub2.[Invoice No];
使用Access 2007和您的示例数据在名为Invoices
的表中,该查询为我提供了此结果集:
Invoice No customers Cust No
708 2 700180
708 2 45001301
如果您确实希望查看所有这些重复发票号的数据,请将第二个查询的第一行更改为:
SELECT i.[Invoice No], sub2.customers, i.[Cust No], i.[Seq No], i.[Input Date]
答案 1 :(得分:0)
怎么样:
SELECT inv.[cust no],
inv.[invoice no],
inv.[seq no],
inv.[input date]
FROM inv
INNER JOIN (SELECT q.[invoice no],
Count(q.[invoice no]) AS [CountOfInvoice No]
FROM (SELECT inv.[invoice no],
inv.[cust no]
FROM inv
GROUP BY inv.[invoice no],
inv.[cust no]) AS q
GROUP BY q.[invoice no]
HAVING (( ( Count(q.[invoice no]) ) > 1 ))) AS q2
ON inv.[invoice no] = q2.[invoice no]
其中inv是表格的名称。
查询返回具有多个关联客户编号的发票编号的所有详细信息和行。
cust no invoice no seq no input date
700180 708 4 30/09/2007
45001301 708 3 30/09/2007
700180 708 2 30/09/2007
700180 708 1 30/09/2007