2016-03-11 90 views
1

我试图获得更高的价格最贵的产品(笔记本电脑,PC或打印机)的。所以我试过这个查询:SQL Server查询不正确过滤

select price 
from 
    (select price, model 
    from printer 

    union 

    select price, model 
    from pc 

    union 

    select price, model 
    from laptop) t 
where 
    price >= All (select t.price); 

但是这会返回所有价格。如果我改变最后一行是:

where price > All (select t.price); 

我没有得到任何结果。

那么为什么呢?我试着最后一行是:where price >= All (select price from t);,但它不起作用(它说t是无效的对象 - 为什么?)。

有人能告诉我如何解决这个查询?

我接受这样做的更好的方法的建议,但我会很感激,如果有人能解决这个问题的查询,并使得它的工作原理。

感谢您的关注

附:我认为(select t.price);不产生价格的整个列表,但我怎么能生成它在该子查询时(select price from t)无效的请求?

+1

要回答你的第一个问题:'选择t.price'是_correlated subquery_。你已经有效地写了'where t.price> = t.price'对于所有非空价格都是'true'。将条款更改为'where t.price> t.price'结果为零行,因为没有价格大于自身。 – HABO

回答

2

尝试MAX功能在查询

select MAX(price) as maximum_price 
from (select price, model from printer 
    union 
    select price, model from pc 
    union 
    select price, model from laptop) t 

对于你的方式固定查询试试下面

select price 
from (select price, model from printer 
    union 
    select price, model from pc 
    union 
    select price, model from laptop) t 
where t.price>= ALL( 
        select price from printer 
         union 
        select price from pc 
         union 
        select price from laptop 

        ) 

同样使用CTE方法:

with t (price,model) as 
(
select price, model from printer 
    union 
    select price, model from pc 
    union 
    select price, model from laptop) 


select price 
from t 
where t.price>= ALL(

        select price from t 

        ) 
+0

为什么在你的最后一个例子中“从t选择价格”起作用? 't'就像现有的表格(从查询的角度来看)。 – DPM

1

一种替代方法,无需where

select top 1 t.* 
from (select price, model from printer 
     union all 
     select price, model from pc 
     union all 
     select price, model from laptop 
    ) t 
order by price desc; 

这可以让你得到模型以及价格。