sql server - Distinct records from multiple queries -
this question has answer here:
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] table1 -- first query zonename = 'name1' union select top 1 [id] table1 -- second query zonename = 'name1' union select top 1 [id] table1 -- third query zonename = 'name1'
result :
id ----- 20011
expected result :
20011 10027 20074
from above query need 3 results each query not overlap each other, in case expected result should contain top 2 query 1 i.e. 20011 , 10027 , next top 1 should exclude 2 results , return 20074 query 2.
note : have used single condition example, in actual query each of query has different conditions, , end having same / different result query above itself.
with w1 ( select top 2 [id] table1 -- first query zonename = 'name1' ), w2 ( select top 1 [id] table1 -- second query zonename = 'name1' , id not in ( select id w1 ) ), w3 ( select top 1 [id] table1 -- second query zonename = 'name1' , id not in ( select id w1 union select id w2 ) ) select * w1 union select * w2 union select * w3
Comments
Post a Comment