我需要找到所有附有重复客户编号的订单。
SalesNo CustNo
112233 56
998877 12
998877 33
110044 312
它应该返回以下结果:
SalesNo CustNo
998877 12
998877 33
我尝试了以下脚本,但我认为这只会让我得到重复输入的具有相同数据的订单。
select salesno, custno, COUNT(*)
from sales
GROUP BY salesno, custno
HAVING COUNT(*) > 1
答案 0 :(得分:2)
您可以比较having
子句中的值:
select salesno, COUNT(*)
from sales
group by salesno
having min(custno) <> max(custno)
答案 1 :(得分:1)
我知道了。发生了以下情况:
select a.salesno, a.custno
from sales a
LEFT JOIN(
select salesno, custno
from sales
)b ON a.salesno = b.salesno
WHERE a.salesno = b.salesno AND a.custno <> b.custno
ORDER BY a.salesno
答案 2 :(得分:0)
您可以使用DISTINCT
关键字:
select salesno, custno, COUNT(*)
from sales
GROUP BY salesno, custno
HAVING COUNT(DISTINCT custno) > 1
答案 3 :(得分:0)
另一种选择是将WITH TIES
与sum() over()
配合使用
示例
Select Top 1 with ties *
from YourTable
Order By sign(sum(1) over (partition by SalesNo) - 1) Desc
返回
SalesNo CustNo
998877 12
998877 33
答案 4 :(得分:0)
您必须首先找到重复的订单号
select salesno
from sales
GROUP BY salesno
HAVING COUNT(*) > 1
然后搜索这些订单的记录
WITH duble AS (
select salesno
from sales
GROUP BY salesno
HAVING COUNT(*) > 1
)
SELECT s.*
FROM sales s
INNER JOIN duble d ON s.salesno=d.salesno
答案 5 :(得分:0)
使用cte(custno,cnt)为( 选择11235,12所有 选择11235,14所有 选择11236,22全部 选择11237,33) 从Custno所在的Cte中选择*(从CTE组中按CUSTNO的COUNT(*)> 1选择Custno)