比如表
name  count
A     10
B     5
C     20
D     60
E     80
F     2
G     7
H     3共8条记录name保证唯一现在要查询count的TOP5,以及剩下3条的总和:E 80
D 60
C 20
A 10
G 7
其它 10希望不要用create temporary tabe

解决方案 »

  1.   

    mysql> create table temp(name char(1),co int);
    Query OK, 0 rows affected (0.13 sec)mysql> insert into temp values ('A',10),('B',5),('C',20),('D',60),('E',80),('F',
    2),('G',7),('H',3);
    Query OK, 8 rows affected (0.03 sec)
    Records: 8  Duplicates: 0  Warnings: 0mysql> select * from temp;
    +------+------+
    | name | co   |
    +------+------+
    | A    |   10 |
    | B    |    5 |
    | C    |   20 |
    | D    |   60 |
    | E    |   80 |
    | F    |    2 |
    | G    |    7 |
    | H    |    3 |
    +------+------+
    8 rows in set (0.00 sec)mysql> select * from  (select * from temp order by co desc limit 0,5 ) a   union
     select '其它' as name , sum(a.co) as co from (select * from temp  order by co d
    esc limit 5,3 ) a;
    +------+------+
    | name | co   |
    +------+------+
    | E    |   80 |
    | D    |   60 |
    | C    |   20 |
    | A    |   10 |
    | G    |    7 |
    | 其它 |   10 |
    +------+------+
    6 rows in set (0.00 sec)
      

  2.   

    select name,count
    from tb
    order by count desc limit 5
    union all
    select '其他',sum(count)
    from tb
    where name not in (select name
    from tb
    order by count desc limit 5)
      

  3.   

    select * from (select * from 比如表 order by `count` desc limit 5) t
    union all
    select '其它',sum(`count`) from 比如表 where name not in (select name from 比如表 order by `count` desc limit 5)
      

  4.   

    SELECT * FROM (SELECT * FROM temp a WHERE 5>(SELECT COUNT(*) FROM temp WHERE a.co<co ) ORDER BY a.co DESC) a
    UNION ALL
    SELECT '其它',SUM(co) FROM temp a WHERE 5<=(SELECT COUNT(*) FROM temp WHERE a.co<co )