Skip to content
Advertisement

How to compare column values in SQL grouped by one column?

I am practicing SQL from a cars database and I have the following CAR table/view and I need to select the brand which sells more cars than engines/motorcycles. This means that I have to select the rows where only UNIT_SOLD for CAR type is greater than the value for ENGINE OR MOTORCYCLE.

For example, in the previous example I have to return:

explanation: the previous brands sells more cars than engine/motorcycle. CHEVY is not considered due that they sells 3 engine and only 1 car.

I have been trying to approach the problem with conditional SELECT statements, however I don not know if that is a good approach.

Thanks so much.

Currently I am able to get the rows where CAR unit_sold ar greater, however still I am not able to get those rows where any number of cars are sold and they do not have any motorcycle/engine sold.

Advertisement

Answer

Using conditional aggregation you can get each total and compare.

SQL DEMO

OUTPUT

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement