如何编写由商家然后由发现的重复项组织的查询?

时间:2019-03-28 15:51:31

标签: sql database self-join

我正在寻找重复的客户ID,并希望按商家显示它们。我知道这需要一个自联接,但不能正确使用语法。

此查询向我显示了重复项。

Select MerchId, CustId, Count(CustId) 
from Customers
Group by MerchId, CustId
Having Count(CustId)> 1

此查询向我显示了特定商人的所有公款。

SELECT  c.MerchId, c.CustId 
FROM Customers c
WHERE CustId IN 
(SELECT c.CustId FROM Customers AS c
WHERE c.MerchId = @mid 
group by c.CustId having count(1) > 1)
and c.MerchId = @mid
order by CustId

但是我想看到的信息显示为:

MerchId, CustId, Address, Phone     
1        01     
1        01     
1        02     
1        02     
1        03     
1        03     
2        01     
2        01     
2        02     
2        02     

假设n个商家有n个客户。 预先感谢

1 个答案:

答案 0 :(得分:0)

您可以将查询加入到表中

select c.merchid, c.custid, c.address, c.phone 
from customers c inner join (
  select merchid, custid 
  from customers
  group by merchId, custId
  having count(custid)> 1
) g on g.merchid = c.merchid and g.custid = c.custid

或通过显式计数每一行(效率较低,但更易于阅读):

select c.merchid, c.custid, c.address, c.phone 
from customers c
where (
  select count(*) from customers
  where merchid = c.merchid and custid = c.custid
) > 1