1

我一生都看不到我在这里缺少什么,但有人可以向我指出为什么第一个查询没有做我想要的,但第二个工作正常吗?我知道查询并不完全相同,但它们应该返回相同的 20 行,但它们没有。(查询填充查找单个表中最常见的前 20 项)

    select distinct
             rx.drug_class
        from rx
        where exists
        (
            select top 20    
                     rx2.drug_class
                    ,COUNT(distinct rx2.pat_id) as counts
                    ,RANK() over(order by count(distinct pat_id) desc) as rn
                    from rx as rx2
                    --when the line below is commented out 
                    --this subquery gives the correct answer
                    where rx.drug_class = rx2.drug_class
                    group by rx2.drug_class
        )

这个工作正常

select distinct 
        rx.drug_class
        from rx
        where rx.drug_class in 
        (
            select top 20 rx.drug_class
                from rx
                group by rx.drug_class
                order by COUNT(distinct pat_id) desc 
        )

Exists 子查询中的 where 子句不起作用,是什么原因?

4

2 回答 2

5

即使您为第一个查询分配了行号,您仍然需要ORDER BY此行号:

where rx.drug_class = rx2.drug_class
group by rx2.drug_class
order by rn

另外,我假设这只是一个简化的示例,因为以下内容也可以:

select top 20 rx.drug_class
from rx
group by rx.drug_class
order by COUNT(distinct pat_id) desc

编辑:

EXISTS也将无法工作,因为您在SELECT执行计数之前将集合限制为内部匹配行与外部集合中的行......因此在这种情况下,该行将始终存在于top 20计数中。

之所以IN有效,是因为它是所有行的一组计数...EXISTS失败是因为正在对外部集合中的每一行进行计数...所以当这些计数时,外部集合中的每一行都在前 20 位仅限于外排的drug_class.

于 2013-03-26T18:17:54.643 回答
1

据我所知,EXISTS子句只返回TRUEFALSE。因此,如果子查询中存在 20 行,则表示TRUEIN ,而不是与子句一样的过滤器。

于 2013-03-26T18:26:48.523 回答