如何编写一个按商家组织然后按找到的重复项组织的查询?
How does one write a query that organizes by merchant then by found duplicates?
我正在寻找重复的 customerid 并希望按商家显示它们。我知道这需要自连接,但语法不正确。
此查询向我显示了重复项。
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 个顾客。
提前致谢
您可以将查询加入 table:
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
我正在寻找重复的 customerid 并希望按商家显示它们。我知道这需要自连接,但语法不正确。
此查询向我显示了重复项。
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 个顾客。 提前致谢
您可以将查询加入 table:
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