带有子查询的SQL Server查询未正确过滤

时间:2016-03-11 23:06:36

标签: sql sql-server tsql union

我正在努力获得最昂贵产品(笔记本电脑,个人电脑或打印机)的更高价格。所以我尝试了这个查询:

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是无效的对象 - 为什么???)。

有人可以告诉我如何修复此查询吗?

我接受有关更好方法的建议,但我会感激如果有人可以修复此查询并使其有效。

感谢您的关注

P.S。我假设(select t.price);没有生成整个价格列表,但是当(select price from t)无效请求时如何在此子查询中生成它?

2 个答案:

答案 0 :(得分: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

                   )

答案 1 :(得分: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;

这使您可以获得模型和价格。