简体   繁体   English

在MySQL查询中选择子项

[英]Sub selects within MySQL query

I am wanting to alias 3 variables in my query, total_time_taken and average and request_count . 我想在查询中给3个变量total_time_taken别名,即total_time_takenaveragerequest_count

The average is meant to calculate the total_time_taken / request_count to return average however it is giving me a syntax error 该平均值用于计算total_time_taken / request_count以返回average但是它给了我一个语法错误

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

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. 另外,您正在使用GROUP BY进行SELECT * ,这通常不起作用,并且通常是错误的,因为它将包括非聚合列。 Instead, just select engineer_id or an aggregate of some other column. 相反,只需选择engineer_id或其他某些列的集合。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM