Merge multiple queries excluding common results

2020-05-10 07:50发布

Data :

--Table 1 :
Id ZoneName
----------- --------
20011       Name1
10027       Name1
20011       Name1
20011       Name1
20011       Name1
20074       Name1
20011       Name2
20011       Name2
10059       Name3
20011       Name2

Query :

 Select Top 2 [Id] From Table1 -- First Query
    WHERE ZoneName = 'Name1'
    UNION
    SELECT Top 1 [Id] from Table1 -- Second Query
    WHERE ZoneName = 'Name1'
    UNION
    SELECT Top 1 [Id] from Table1 -- Third Query
    WHERE ZoneName = 'Name1'

Result :

Id
-----
20011    

Expected Result :

20011
10027
20074

From the above query I need 3 results from each query that do NOT overlap each other, in this case the expected result should contain the top 2 for query 1 i.e. 20011 and 10027 and for the next top 1 it should exclude those 2 results and return 20074 for query 2.

Note : I have used a single WHERE condition for this example, however in the actual query each of the query has different Where conditions, and could end up having same / different result from the query above itself.

1条回答
家丑人穷心不美
2楼-- · 2020-05-10 08:17

As far as I know If you are searching to query distinct Id's for a particular ZoneName then this may work out

SELECT DISTINCT ID
FROM TABLE1
WHERE ZoneName="Name1"
查看更多
登录 后发表回答