现有字段:
id,fromplace,toplace,scount,logyear,logmonth备注:
fromplace:出发地
toplace:目的地
scount:搜索次数
logyear:记录年
logmonth:记录月现在想用一条SQL语句查询每年每个月中,搜索次数在前20的记录

解决方案 »

  1.   


    select * 
    from tb t
    where id
    in (select top 20 id from tb where t.logyear=logyear and t.logmonth=logmonth
     order by scount desc)
      

  2.   

    修改
    现有字段:
    id,stype,fromplace,toplace,scount,logyear,logmonth备注:
    stype:搜索类型
    fromplace:出发地
    toplace:目的地
    scount:搜索次数
    logyear:记录年
    logmonth:记录月现在想用一条SQL语句根据搜索类型查询每年每月中,搜索次数在前20的记录
      

  3.   

    select * from tb where 20>
    (select count(*) from tb 
       where ltrim(logyear)+ltrim(logmonth)=a.ltrim(logyear)+a.ltrim(logmonth)
           and 搜索次数 >a.搜索次数)
      

  4.   


    SELECT * FROM TABLENAME 
    WHERE ID IN (SELECT TOP 20 ID FROM TABLENAME ORDER BY SCOUNT DESC)
      

  5.   

    不知道这样的效率怎么样select * 
    from tb t
    where id
    in (select top 20 id from tb 
        where stype = t.stype and t.logyear=logyear and t.logmonth=logmonth
     order by scount desc)
      

  6.   

    http://topic.csdn.net/u/20100331/10/92922401-3c5a-48cc-ba20-57c47305f676.html?5312
      

  7.   

    tryselect * from tb t
    where id in (select top 20 id from tb where t.logyear=logyear and t.logmonth=logmonth
     order by scount desc)
      

  8.   


    select * from tb t
    where id in (select top 20 id from tb where t.logyear=logyear and t.logmonth=logmonth
     order by scount desc)效率有点慢已经统计好的次数
      

  9.   


    select *
    from
    (
    select fromplace,toplace,scount,logyear,logmonth,
    rownum=row_number() over(partition by logyear,logmonth order by scount desc)
    from table
    ) t
    where rownum<20
      

  10.   


    ;with cte as
    (
    select fromplace,toplace,scount,logyear,logmonth,
    rownum=row_number() over(partition by logyear,logmonth order by scount desc)
    from tablename
    )select * from cte where rownum between 1 and 20   --这里指定第几到第几
      

  11.   

    --sql 2005 利用ROW_NUMBER是分组取数最快 接着是APPLY
    ;with cte as
    (
    select *,rn=ROW_NUMBER() over(partition by rtrim(logyear)+'-'+rtrim(logmonth)order by scount desc)
    from tb 
    )
    select stype,scount ,rtrim(logyear)+'-'+rtrim(logmonth)
    from cte 
    where rn<=20
      

  12.   


    --sql2000没有row_number函数 及不支持cte,用下面语句
    select * from 
    (select *,
    rownum=(select count(1) from tablename where logyear=t.logyear and logmonth=t.logmonth and scount>=t.scount)
    from tablename t
    ) tt
    where rownum between 1 and 2  --这里指定第几到第几