2

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 中绘制模型/模型,它有一个最高价格

我可以通过添加到选择子句来轻松选择最高价格 - max(G.price),但我需要模型并且只有模型......

什么语法是正确的?

先感谢您!

4

4 回答 4

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”,因为只需要一条记录
  • 编辑 2:删除“前 1”,添加排名
  • 编辑 3:使用 sqlfiddle 后删除了“按模型分区”。谢谢@bluefeet!
  • 编辑 4:添加了替代“与领带”。再次感谢@bluefeet。
于 2013-01-02T19:30:09.623 回答
1

这是有效的解决方案..

从电脑选择型号,其中价格 >= 全部(从电脑联合选择最大(价格)从笔记本电脑联合选择最大(价格)从打印机)

联盟

SELECT model FROM laptop WHERE price >= ALL(SELECT MAX(price) FROM pc UNION SELECT MAX(price) FROM laptop UNION SELECT MAX(price) FROM printer)

联盟

SELECT model FROM printer WHERE price >= ALL(SELECT MAX(price) FROM pc UNION SELECT MAX(price) FROM laptop UNION SELECT MAX(price) FROM printer)

于 2013-01-03T14:14:45.417 回答
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。

于 2013-01-02T19:45:24.123 回答
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
于 2013-01-02T20:01:38.073 回答