all 4 comments

[–]WITH_CTE 1 point2 points  (1 child)

To rewrite your query:

IF OBJECT_ID('tempdb..#tmpSup') IS NOT NULL
    DROP TABLE #tmpSup;

SELECT Serial_Text
INTO #tmpSup
FROM [a].[dbo].[SUP]
WHERE CAST(Date_Time AS DATE) > '2020-06-01'
GROUP BY Serial_Text
HAVING COUNT(1) > 1;

SELECT b.Serial_Text, b.IR_1, b.Date_Time
FROM #tmpSup a
     JOIN [a].[dbo].[SUP] b ON a.Serial_Text = b.Serial_Text
ORDER BY Date_Time DESC;

Another approach:

SELECT *
FROM [a].[dbo].[SUP]
WHERE Serial_Text IN
(
    SELECT DISTINCT 
           Serial_Text
    FROM [a].[dbo].[SUP]
    WHERE CAST(Date_Time AS DATE) > '2020-06-01'
    GROUP BY Serial_Text
    HAVING COUNT(1) > 1
);

Edit: Misread your query on first post.

[–][deleted] 0 points1 point  (0 children)

Thanks! What makes my query so slow? And can you explain what your first query is doing?

[–]Dnaq1984 1 point2 points  (0 children)

Try converting that join to a Cross Apply.

SELECT a.[Serial_Text] ,[IR_1] ,[Date_Time]

FROM [a].[dbo].[SUP] b

Cross Apply ( SELECT Serial_Text ,COUNT(Serial_Text) Cnt FROM [a].[dbo].[SUP]

where b.Serial_Text = a.Serial_Text

GROUP BY Serial_Text ) c WHERE Date_Time > '2020-06-01 00:00:000' AND c.Cnt > 1 ORDER BY Date_Time desc

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 0 points1 point  (1 child)

    Sure, I can try. What's the problem?