合并多个查询,不包括常见结果 [英] Merge multiple queries excluding common results

查看:29
本文介绍了合并多个查询,不包括常见结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据:

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

查询:

 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'

结果:

Id
-----
20011    

预期结果:

20011
10027
20074

从上面的查询中,我需要每个查询的 3 个结果彼此不重叠,在这种情况下,预期结果应包含查询 1 的前 2 个,即 20011 和 10027,对于下一个前 1 个,它应排除那些 2 个结果并为查询 2 返回 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.

注意:我在此示例中使用了单个 WHERE 条件,但是在实际查询中,每个查询都有不同的 Where 条件,并且最终可能会得到与上面的查询相同/不同的结果.

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.

推荐答案

据我所知,如果您正在搜索查询特定 ZoneName 的不同 Id,那么这可能会解决

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"

这篇关于合并多个查询,不包括常见结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆