Query design in SQL - ORDER BY SUM() of field in rows which meet a certain condition

Posted by Christian Mann on Stack Overflow See other posts from Stack Overflow or by Christian Mann
Published on 2010-03-30T23:05:55Z Indexed on 2010/03/30 23:13 UTC
Read the original article Hit count: 471

Filed under:
|
|
|
|

OK, so I have two tables I'm working with - project and service, simplified thus:
project
-------
id PK
name str

service
-------
project_id FK for project
time_start int (timestamp)
time_stop int (timestamp)

One-to-Many relationship.

Now, I want to return (preferably with one query) a list of an arbitrary number of projects, sorted by the total amount of time spent at them, which is found by SUM(time_stop) - SUM(time_start) WHERE project_id = something.

So far, I have
SELECT project.name
FROM service
LEFT JOIN project ON project.id = service.project_id
LIMIT 100

but I cannot figure out how what to ORDER BY.

© Stack Overflow or respective owner

Related posts about sql

Related posts about query