一个查询中MySQL最常见的列值和AVG

时间:2018-10-24 21:11:06

标签: mysql count average

我有一张表,其中的列包含有关风(风,阵风和风向)的数据

我希望在选定的时间段获得风和阵风的平均值以及方向的最常用值

我可以在两个查询中做到这一点,但是不知道如何合并它们

SELECT
    avg(wind) as wind,
    avg(gust) as gust
FROM
    station
WHERE
    id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00'

SELECT
    direction,
    count(direction) as sm
FROM
    station
WHERE
    id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00'
GROUP BY
    direction
ORDER BY
    sm DESC LIMIT 1

我尝试过

SELECT
    avg(wind) as wind,
    avg(gust) as gust,
    direction,
    count(direction) as sm
FROM
    station
WHERE
    id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00'
GROUP BY
    direction
ORDER BY
    sm DESC LIMIT 1

但这将计算数据的平均值,但仅在方向是最常见的值的情况下。感谢帮助

1 个答案:

答案 0 :(得分:0)

您可以尝试一下。

SELECT direction,
       t1.wind,
       t1.gust,
       count(direction) as sm
FROM station CROSS JOIN (
    SELECT avg(wind) as wind,
           avg(gust) as gust 
    FROM station 
    WHERE id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00' 
) t1
WHERE id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00' 
GROUP BY direction 
ORDER BY sm DESC 
LIMIT 1

或者您可以在select

中使用子查询
SELECT direction,
       (select avg(wind) FROM station) wind,
       (select avg(gust) FROM station) gust,
       count(direction) as sm
FROM station 
WHERE id >='2018-10-20 00:00:00' AND id <'2018-10-20 04:00:00' 
GROUP BY direction 
ORDER BY sm DESC 
LIMIT 1