Skip to content
Advertisement

Percentage calculation in SQL

I have some cars in a table along with the year they came out, and I’m trying to calculate the percentages of the cars that belong in the 4 following age groups: 0-4, 5-9, 10-19, 20+.

I tried to do this in 3 different ways:

1.

I got this error:

I got this error:

I got this error:

Any ideas on what I could do? I’m using pgadmin4 and PostgreSQL 13

Advertisement

Answer

Give your columns more reasonable names! Then for the calculation:

Note the changes to the query:

  • The column aliases are simple identifiers and do not need to be escaped. Highly recommended.
  • The calculation uses AVG() to get a ratio rather than SUM() for a count. That is what your question claims you want.
  • Table aliases make the query easier to write and to read. Hence the v.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement