查找重复的元素

时间:2018-12-13 20:59:31

标签: sql

我有一个计数,在这里我检测到重复不止一次的元素。

select MstDocCabId, count (*) as 'Repetition Number'
from skmov (nolock)
group by MstDocCabId
having count(MstDocCabId) > 1

因此,结果类似于:

+-------------+-------------------+
| MstDocCabId | Repetition Number |
+-------------+-------------------+
| 16513519    | 4                 |
+-------------+-------------------+

因此,如果我使用select * from skmov where MstDocCabId=16513519,则可以看到4个具有相同mstdoccabid的元素,例如

+----------+----------+
|  MstID   |   Col2   |
+----------+----------+
| 38600690 | 16513519 |
| 38600691 | 16513519 |
| 38600692 | 16513519 |
| 38600693 | 16513519 |
+----------+----------+

对于每一个重复 mstdoccabid 的行,都有一个名为 product 的列,对于每种情况,该列可能具有或应该具有不同的值:

+-----------+-------------+---------+
| MstID     | mstdoccabid | Product |
+-----------+-------------+---------+
| 38600690  | 16513519    | AAAA    |
| 38600691  | 16513519    | BBBB    |
| 38600692  | 16513519    | CCCC    |
| 38600693  | 16513519    | DDDD    |
+-----------+-------------+---------+

我的问题是如何检测重复出现 mstdoccabid product 相同的情况(例如产品AAAA)。

+-----------+-------------+---------+
| MstID     | mstdoccabid | Product |
+-----------+-------------+---------+
| 38600690  | 16513519    | AAAA    |
| 38600691  | 16513519    | BBBB    |
| 38600692  | 16513519    | CCCC    |
| 38600693  | 16513519    | AAAA    |
+-----------+-------------+---------+

1 个答案:

答案 0 :(得分:0)

也可以按Product分组,它将起作用:

select MstDocCabId, count (*) as 'Repetition Number'
from skmov (nolock)
group by MstDocCabId, Product
having count(MstDocCabId) > 1