0

I am wanting to alias 3 variables in my query, total_time_taken and average and request_count.

The average is meant to calculate the total_time_taken / request_count to return average however it is giving me a syntax error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, r' at line 4

The query is below.

select
    *,
    COUNT(*) as request_count,
    select(created_at, assigned_at, SUM(TIMESTAMPDIFF(SECOND, requests.created_at, requests.assigned_at)) from requests) as total_time_taken,
    total_time_taken / request_count as average
from
    `requests`
where
    `deleted_at` is null
and
    `submitted_at` >= '2017-03-30 00:00:00'
and
    `requests`.`deleted_at` is null
group by
    `engineer_id`
limit 5
2
  • You are missing an ( in front of the 2nd select Commented Apr 3, 2017 at 9:10
  • the sub select needs to be wrapped in ()? @Shadow Commented Apr 3, 2017 at 9:12

1 Answer 1

1

I don't see the point of the subqueries, why not just take the sum as you aggregate by each engineer? Alse, you were doing SELECT * with GROUP BY, which usually doesn't work, and usually is wrong, because it would include non aggregate columns. Instead, just select engineer_id or an aggregate of some other column.

SELECT
    engineer_id,
    COUNT(*) AS request_count,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) AS total_time_taken,
    SUM(TIMESTAMPDIFF(SECOND, created_at, assigned_at)) /
    COUNT(*) AS average
FROM requests
WHERE deleted_at IS NULL AND
      submitted_at >= '2017-03-30 00:00:00' AND
      deleted_at IS NULL
GROUP BY engineer_id
LIMIT 5
Sign up to request clarification or add additional context in comments.

3 Comments

Getting the error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT SUM(TIMESTAMPDIFF(SECOND, requests.created_at, requests.assigned_at)) / ' at line 5 However you have nailed exactly what I want to do.
You probably want to use ORDER BY with this query, since you are using LIMIT. As it stands now, you would be returning 5 arbitrary engineers, probably not what you want.
As I mentioned above, add ORDER BY <something> to the end of the query to get five engineers according to some order, assuming you want that.

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.