DB中有几个表:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, price, screen)
Printer(code, model, color, type, price)
我需要找到
以最高价格查找产品(PC,笔记本电脑或打印机)的型号。 结果集:模型。
我设法编写了以下查询:
select model from
(select model, price from PC
union
select model, price from Laptop
union
select model, price from Printer) G
现在我需要绘制集合G中的模型/模型,它具有最高价格
我可以通过添加到select子句 - max(G.price),轻松选择最高价格, 但我需要模型,只需要模型......
什么语法是对的?
提前谢谢你!
答案 0 :(得分:1)
仅限最高价格?
select model
from
(select
model,
rank() over (order by max(price) desc) as [rank]
from
(select model, price from PC
union
select model, price from Laptop
union
select model, price from Printer) u
group by model) g
where g.rank = 1
对不起,但我目前无法测试是否可以在rank()中使用MAX()。如果没有,请添加另一个子查询。首先确定最高(价格),然后确定等级。
所以,RANK()里面的MAX()正在工作...... 另一种选择,语法简单:
select top 1 with ties
g.model
from
(select
u.model,
max(u.price) as [maxPrice]
from
(select model, price from PC
union
select model, price from Laptop
union
select model, price from Printer) u
group by model) g
order by g.maxPrice desc
答案 1 :(得分:1)
这是有效的解决方案..
SELECT模型 来自电脑 价格> =全部(SELECT MAX(价格)FROM pc UNION SELECT MAX(价格)FROM笔记本电脑UNION SELECT MAX(价格)FROM打印机)
UNION
SELECT模型 从笔记本电脑 价格> =全部(SELECT MAX(价格)FROM pc UNION SELECT MAX(价格)FROM笔记本电脑UNION SELECT MAX(价格)FROM打印机)
UNION
SELECT模型 从打印机 价格> =全部(SELECT MAX(价格)FROM pc UNION SELECT MAX(价格)FROM笔记本电脑UNION SELECT MAX(价格)FROM打印机)
答案 2 :(得分:0)
以Jacco的答案为基础,
select model
from
(select model, max(price) as maxPrice
from
(select model, price from PC
union
select model, price from Laptop
union
select model, price from Printer) u
group by model) g
where maxPrice = max(maxPrice)
更改为限制1而不是mysql。
答案 3 :(得分:0)
SELECT
model
FROM
(
SELECT model, price, ROW_NUMBER() OVER(ORDER BY price DESC) AS seq FROM PC
UNION
SELECT model, price, ROW_NUMBER() OVER(ORDER BY price DESC) AS seq FROM Laptop
UNION
SELECT model, price, ROW_NUMBER() OVER(ORDER BY price DESC) AS seq FROM Printer
) final
WHERE
seq = 1