Trouble with MySQL query using AVG()

后端 未结 2 1880
爱一瞬间的悲伤
爱一瞬间的悲伤 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 04:02

    Another option is to simulate ROW_NUMBER().

    This statement creates a counter and resets it every time it encounters a new bline_id. It then filters out any records that aren't in the first 10 rows.

    SELECT bline_id, 
           Avg(flow) avg 
    FROM   (SELECT id, 
                   bline_id, 
                   flow, 
                   date, 
                   CASE 
                     WHEN @previous IS NULL 
                           OR @previous = bline_id THEN @rownum := @rownum + 1 
                     ELSE @rownum := 1 
                   end rn, 
                   @previous := bline_id 
            FROM   blf, 
                   (SELECT @rownum := 0, 
                           @previous := NULL) t 
            WHERE bline_id > 0 and bline_id < 31
            ORDER  BY bline_id, 
                      date DESC, 
                      id) t 
    WHERE  rn < 11
    GROUP  BY bline_id 
    

    DEMO

    It's worthwhile seeing this in action by removing the group by and looking at intermediate results

提交回复
热议问题