[英]Tricky “grouped” ordering in SQL
Been having trouble with this for some time. 一段时间以来一直遇到麻烦。
I have a database sort of like this: 我有一个像这样的数据库:
Car_ID Car_Brand Car_Model Car_Price
1 Ford Fiesta 4000
2 Ford Mustang 29000
3 Ford Focus 12000
4 Honda Civic 15000
6 Honda Jazz 5000
7 Toyota Prius 14000
I want to perform a search that finds the cheapest car then orders the rest of the cars of the same brand by price ascending. 我想进行搜索,找到最便宜的汽车,然后通过价格上涨来订购同一品牌的其他汽车。
I want my output to be this: 我希望我的输出是这样的:
Car_ID Car_Brand Car_Model Car_Price
1 Ford Fiesta 4000
3 Ford Focus 12000
2 Ford Mustang 29000
6 Honda Jazz 5000
4 Honda Civic 15000
7 Toyota Prius 14000
The cheapest car is the Ford Fiesta so that and the rest of the Ford models follow it directly ordered by price. 最便宜的车是福特嘉年华,所以其他福特车型按照价格直接订购。 Honda then has the second cheapest model so the Jazz and the rest of the Hondas follow and so on.
然后本田拥有第二个最便宜的车型,所以爵士乐和其他本田车队紧随其后。
Is this possible? 这可能吗?
What you need to do is create a transient data set that contains car_brand and the lowest price for that brand (which I'll call brand_price), then JOIN that data back to your original cars table. 您需要做的是创建一个瞬态数据集,其中包含car_brand和该品牌的最低价格(我将其称为brand_price),然后将该数据加入到原始汽车表中。 This will give you the additional piece of information (brand_price) that you need to sort the data:
这将为您提供排序数据所需的额外信息(brand_price):
SELECT car_id, car_brand, car_model, price FROM cars C1
JOIN (select car_brand, MIN(price) AS brand_price FROM cars GROUP BY car_brand) C2
ON C1.car_brand = C2.car_brand
ORDER BY C2.brand_price, C1.car_brand, C1.price
Something like this should work: 这样的事情应该有效:
SELECT a.*
FROM Cars a
LEFT JOIN (
SELECT Car_Brand, MIN(Car_Price) AS MinPrice
FROM Cars
GROUP BY Car_Brand
) b ON a.Car_Brand = b.Car_Brand
ORDER BY b.MinPrice, a.Car_Price
I would do a min grouped by Car_Brand order by the min price and then do a join ordered by the sorted car_brand and price. 我会按照最低价格按Car_Brand顺序进行分组,然后按分类的car_brand和价格进行订购。 I will see if I can get the query done for this.
我会看看我是否可以为此完成查询。
I think you will be able to do that with the following query 我想你可以用以下查询来做到这一点
SELECT Car_ID, Car_Brand, Car_Model, Car_Price
FROM tblcars
ORDER BY Car_Price, Car_Brand
unless I missed something 除非我错过了什么
select * from cars order by Car_Price, Car_Brand ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.