SQL 带有子查询的服务器查询过滤不正确
SQL Server query with subquery not filter correctly
我正在尝试以更高的价格购买最昂贵的产品(笔记本电脑、个人电脑或打印机)。所以我尝试了这个查询:
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);
但是这个returns我所有的价格。如果我将最后一行更改为:
where price > All (select t.price);
我没有得到任何结果。
那是为什么呢?我试过最后一行是:where price >= All (select price from t);
,但它不起作用(它说 t 是无效对象 - 为什么???)。
谁能告诉我如何解决这个问题?
我接受有关更好的方法的建议,但如果有人可以修复此查询并使其正常工作,我将不胜感激。
感谢您的关注
P.S。我假设 (select t.price);
不会生成整个价格列表,但是当 (select price from t)
不是有效请求时,如何在此子查询中生成它?
在查询中尝试 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
)
没有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;
这可以让您获得型号和价格。
我正在尝试以更高的价格购买最昂贵的产品(笔记本电脑、个人电脑或打印机)。所以我尝试了这个查询:
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);
但是这个returns我所有的价格。如果我将最后一行更改为:
where price > All (select t.price);
我没有得到任何结果。
那是为什么呢?我试过最后一行是:where price >= All (select price from t);
,但它不起作用(它说 t 是无效对象 - 为什么???)。
谁能告诉我如何解决这个问题?
我接受有关更好的方法的建议,但如果有人可以修复此查询并使其正常工作,我将不胜感激。
感谢您的关注
P.S。我假设 (select t.price);
不会生成整个价格列表,但是当 (select price from t)
不是有效请求时,如何在此子查询中生成它?
在查询中尝试 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
)
没有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;
这可以让您获得型号和价格。