简体   繁体   中英

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. This will give you the additional piece of information (brand_price) that you need to sort the data:

 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM