Sql-server – get an equivalent query for this Not in Query

aggregateoptimizationperformancequery-performancesql servertime

SELECT ID FROM dbo.SomeTable
            WHERE ID not in
            (
                SELECT MIN(ID)
                FROM dbo.SomeTable
                GROUP BY SystemNo
            )

As this query is taking very long (more than a minute) to get executed. I guess "IN" is the culprit for this. I would like a query which yield same result but with most efficient time.

Best Answer

You don't select those ids that are minimum in their systemno group so you select only those that have a lower id in their group:

SELECT id FROM dbo.SomeTable st1
WHERE EXISTS
  (
    SELECT *
    FROM dbo.SomeTable st2
    WHERE st1.SystemNo = st2.SystemNo AND st2.id < st1.i
  )