在我的数据库中,我试图找到每个制造商的最高价格模型。我想做一个查询,这样我的输出就会列出制造商、型号和价格。到目前为止,我可以得到制造商的输出和价格,但我不确定要做什么才能让我的模型显示在结果中。
以下是我的代码和当前输出:
Select Product.Maker, Max(U.price)
From (SELECT Price price, Model model
From Desktop
UNION ALL
SELECT Price price, Model model
From Laptop
UNION ALL
SELECT Price price, Model model
From Printer) as U
INNER JOIN Product
ON Product.Model = U.model
GROUP BY Product.Maker输出:
Maker Max(U.price)
A 899
B 1099
C 1399
D 1699
E 1599
F 1799
G 1899
H 80
I 259我希望此输出在制造商和价格旁边显示型号,例如:
Maker Price Model
x y z这是数据库模式,希望能对您有所帮助!任何帮助都将不胜感激。
Computer Database schemas:
Product( maker, model, type)
Desktop( model, speed, ram, hd, price)
Laptop( model, speed, ram, hd, screen,price)
Printer( model, color, type, price)我将能够张贴所有信息的表格,如果这也是有帮助的。
发布于 2017-03-08 05:16:12
你已经走上正轨了。您只需要提取每个Maker的顶行。使用group_concat,您可以将模型列汇总到每个制造商的逗号分隔字符串中,并按其价格排序:
group_concat(Model order by Price desc)这将为您提供所有型号,首先是价格最高的型号。然后,使用substring_index -它获取逗号之前的第一个单词-您只能提取出第一个模型。
select
Maker,
substring_index(
group_concat(Model order by Price desc), ',',1) model,
max(Price) Price
from (
Select Product.Maker Maker, Product.Model Model, Max(U.price) Price
From (SELECT Price price, Model model
From Desktop
UNION ALL
SELECT Price price, Model model
From Laptop
UNION ALL
SELECT Price price, Model model
From Printer) as U
INNER JOIN Product ON Product.Model = U.model
GROUP BY Product.Maker, Product.Model
) t
group by Maker有关概念的解释,请参阅此页面:Selecting Only One Row Per Group
https://stackoverflow.com/questions/42655407
复制相似问题