Trouble with MySQL query using AVG()

后端 未结 2 1900
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 03:13

I am using a query that takes an average of all the records for each given id...

$query = \"SELECT bline_id, AVG(flow) as flowavg 
          FROM blf 
                   


        
2条回答
  •  感情败类
    2021-01-24 03:39

    If these are really updated every day, then use date arithmetic:

    SELECT bline_id, AVG(flow) as flowavg
    FROM blf
    WHERE bline_id BETWEEN 1 AND 30 and
          date >= date_sub(now(), interval 10 day)
    GROUP BY bline_id
    ORDER BY bline_id ASC
    

    Otherwise, you have to put in a counter, which you can do with a correlated subquery:

    SELECT bline_id, AVG(flow) as flowavg
    FROM (select blf.*,
                 (select COUNT(*) from blf blf2 where blf2.bline_id = blf.bline_id and blf2.date >= blf.date
                 ) seqnum
          from blf
         ) blf
    WHERE bline_id BETWEEN 1 AND 30 and
          seqnum <= 10
    GROUP BY bline_id
    ORDER BY bline_id ASC
    

提交回复
热议问题