1

我试图限制用于在 SQL 中进行计算的行数;

SELECT    SUM(`position`)/COUNT(`id`) AS `avg`
FROM      rankings_04_06_13
WHERE     site_id = '7'
ORDER BY  `position` ASC
LIMIT     4

但是,当我这样做并不会改变答案时,就好像计算在到达 LIMIT 和 ORDER BY 子句之前已经发生了一样。

有任何想法吗?

4

4 回答 4

1

试试这个(就像@DekDekku 建议的那样):

SELECT
    SUM(`position`)/COUNT(`id`) AS `avg`
FROM (
    SELECT    `position`,
              `id`
    FROM      rankings_04_06_13
    WHERE     site_id = '7'
    ORDER BY  `position` ASC
    LIMIT 4
) as tmp

更新:要限制 75% 的行,你可以试试这个(但效率不高):

SET @c:=0;    
SELECT
    SUM(`position`)/COUNT(`id`) AS `avg`
FROM (
    SELECT    
        `position`,
        `id`,
        @c:=@c+1,
        MOD(@c,4) as m      
    FROM      
        rankings_04_06_13
    WHERE     
        site_id = '7'
) as tmp
WHERE
    m <> 3 
于 2013-06-05T07:30:59.400 回答
1

这是一个使用派生表的示例。这可能是您要查找的内容,具体取决于您要如何应用限制(您可能希望group by position获得前 4 个位置而不是前 4 行)

SELECT SUM(`position`)/COUNT(`id`) AS `avg` 
FROM   (SELECT position, id 
        FROM rankings_04_06_13 
        WHERE site_id = '7' 
        ORDER BY `position` ASC 
        LIMIT 4
) AS AVRG

SQL小提琴

于 2013-06-05T07:31:37.477 回答
0

试试这个

 SELECT SUM(`position`)/COUNT(`id`) AS `avg`
 FROM   (SELECT position,id from rankings_04_06_13 
 WHERE site_id = '7' 
 ORDER BY  `position` ASC LIMIT 4) as t2
于 2013-06-05T07:31:28.440 回答
0
SELECT    SUM(`position`)/COUNT(`id`) AS `avg` 
FROM      (SELECT postion,id from rankings_04_06_13  
WHERE     site_id = '7' 
ORDER BY  `position` ASC LIMIT 4) AS subquery;
于 2013-06-05T07:33:25.957 回答