查找SQL中一个字段不同的重复记录

时间:2018-04-19 20:36:43

标签: sql

我想找到重复的ticket_id,其中source列不同但ticket_id相同(见下图,哪些记录为红色)

这是表结构

enter image description here

这就是我试过的

SELECT ticket_id, SOURCE, COUNT(ticket_id) AS NumOccurrences
FROM mytable
GROUP BY ticket_id, SOURCE
HAVING ( COUNT(ticket_id) > 1 )

2 个答案:

答案 0 :(得分:0)

您可以对ticket_id进行分组,并仅过滤那些源数大于1的源。

   SELECT * 
   FROM mytable 
   WHERE Ticket_ID IN (
        SELECT Ticket_ID
        FROM mytable
        GROUP BY Ticket_ID
        HAVING COUNT(DISTINCT Source) > 1)

以上返回实际行。如果你只需要计数,你可以

SELECT Ticket_ID, COUNT(1)
FROM mytable
GROUP BY Ticket_ID
HAVING COUNT(DISTINCT source) > 1

答案 1 :(得分:0)

这应该有效:

SELECT d.Ticket_ID, COUNT(*)
FROM(
   SELECT DISTINCT Ticket_ID, Source
   FROM dups  
 ) d GROUP BY ticket_id 
HAVING COUNT(*) > 1 

如果您希望查询返回Ticket_ID和Source,则可以执行以下操作:

SELECT a.* FROM dups a
JOIN( 
    SELECT d.Ticket_ID, count(*)
    FROM(
       SELECT distinct Ticket_ID, Source
       FROM dups  
     ) d GROUP BY ticket_id 
     HAVING COUNT(*) > 1 
) b on a.Ticket_ID = b.Ticket_ID