现在我的数据库中存有商品信息,每个商品有产品名称字段,点击量字段(统计用户访问量),有所属公司字段,我想实现这样一种查询:
依次列出每个公司人气最高的商品,然后列出人气次之的商品……,举例说明:(visit代表访问量)
id    name  visit   company
1      a      3        A
2      b      4        B
3      c      6        A
4      d      5        A
5      e      9        B
6      f      10       B
我想查询出的结果顺序是:c f d e a b
即按照A公司最高,B公司最高,A公司第二高,B公司第二高……的顺序,当然数据库中还有很多公司,这里只举例说明。
请教各位该怎样写查询语句或者有别的实现办法
感谢!

解决方案 »

  1.   

    mysql> select * from t_pengpeng5047;
    +----+------+-------+---------+
    | id | name | visit | company |
    +----+------+-------+---------+
    |  1 | a    |     3 | A       |
    |  2 | b    |     4 | B       |
    |  3 | c    |     6 | A       |
    |  4 | d    |     5 | A       |
    |  5 | e    |     9 | B       |
    |  6 | f    |    10 | B       |
    +----+------+-------+---------+
    6 rows in set (0.00 sec)mysql> select name
        -> from t_pengpeng5047 t
        -> order by (
        ->  select count(*)
        ->  from t_pengpeng5047
        ->  where company=t.company
        ->  and visit>=t.visit), company;
    +------+
    | name |
    +------+
    | c    |
    | f    |
    | d    |
    | e    |
    | a    |
    | b    |
    +------+
    6 rows in set (0.05 sec)mysql>
      

  2.   

    select 
      name
    from
      (select *,(select count(1) from tb where company=t.company and visit>t.visit) as px from tb t) tt
    order by 
      px
      

  3.   

    select * from 表 order by company,visit desc
      

  4.   

    按各分组排序问题,用1、2楼的方法均可,有些数据库中直接用over函数就可以处理