Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using average in query (PostgreSQL)

I'm having trouble with coming up with a query to find the average age of the buses used for each bus company from the following schema:

buscompany

company_id | name
 1           NED
 2           JIM

bustype

type_id | date_made
 1        2006-01-26
 2        1999-05-05
 3        2000-09-01

route

route_id | bustype | bus_company
 1         2         1
 2         1         1
 3         1         1
 4         3         2
 5         3         2
 6         1         2
 7         2         2

In this example NED's average bus age is 4246.666 = 4247 days assuming today is 2013-03-18.

What would the whole query look like?

like image 653
PangolinKing Avatar asked Oct 22 '22 14:10

PangolinKing


1 Answers

I can't test right now, but something like:

-- assuming "date_made" is a pg DATE column
--
   SELECT buscompany.name, ROUND(AVG(CURRENT_DATE - date_made))
     FROM buscompany
LEFT JOIN route
          ON route.bus_company = buscompany.company_id
LEFT JOIN bustype
          ON route.bustype = bustype.type_id
 GROUP BY 1

ought to Do What You Want (tm). Date subtraction in pg gives the difference in days.

like image 191
pilcrow Avatar answered Oct 27 '22 01:10

pilcrow