0

Okay, i've been trying it for a while and haven't succeeded yet, it's kind of mystical, so please help.

vehicle table

Here is my table. I need to select all distinct models and group/order them by the vehicle_type. Everything is ok until I start using DISTINCT. I'm using postgres Little help with query please?

8
  • 5
    Please provide what you have tried so far. Commented Nov 30, 2011 at 17:40
  • 5
    Show us some SQL that you tried and also why it doesn't work Commented Nov 30, 2011 at 17:41
  • 1
    Please provide a sample of the output you are looking for Commented Nov 30, 2011 at 17:42
  • 2
    I think the homework tag should be added. Commented Nov 30, 2011 at 17:42
  • Oh sorry i haven't described the main problem) Which is the vehicle_type values: sm_car, med_car, lge_car and sm_van, med_van, lge_van. So i don't know how to group "cars" and "vans" separately. Commented Nov 30, 2011 at 17:55

2 Answers 2

2

Assuming model could be shared between several vehicle types:

SELECT vehicle_type,model 
FROM vehicle 
GROUP BY vehicle_type,model 
ORDER BY vehicle_type,model
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I don't understand your comment... perhaps it got truncated?
Oh sorry i haven't described the main problem) Which is the vehicle_type values: sm_car, med_car, lge_car and sm_van, med_van, lge_van. So i don't know how to group "cars" and "vans" separately
1

The data model does not adequately capture your reporting requirments as the column data needs to be inspected to categorise it but something like: (Extrapolating a possible relationship from your description)

SELECT CASE (vt.description ~ 'car$') 
       WHEN TRUE THEN 'car'
                 ELSE 'van' 
       END AS vehicle_group,
       vt.description AS vehicle_sub_group,
       COUNT (*) -- or whatever aggregates you might need
  FROM vehicle v
       INNER JOIN vehicle_type vt ON vt.vehicle_type = v.vehicle_type
 GROUP BY 1,2;

Might get you towards what you need in the stated case, however it is a fragile way of dealing with data and will not cope well with additional complexities e.g. if you need to further split car into saloon car, sports car, 4WD or van into flatbed, 7.5 ton, 15 ton etc.

1 Comment

yeap, you're right, I've changed the data model so it is more flexible now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.