Merge multiple queries excluding common results

这一生的挚爱 提交于 2019-12-03 00:35:45

问题


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:


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"


来源:https://stackoverflow.com/questions/18242498/merge-multiple-queries-excluding-common-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!