http://topic.csdn.net/u/20090727/15/9ed67fff-9b1b-419e-a3c0-73daf0bff9b9.html?seed=471792301&r=58644993#r_58644993有一表t1(codeid int,FQ decimal(18,2), fid int identity(1,1) 
insert into t1(codeid,fq) 
select 1,200  
union all 
select 2,300 
union all 
select 1,400 
union all 
select 2,100 
................ 现在按如下要求:注意 codeid 有重复值
按照FID从小到大(升序)sum(fq),将符合sum(fq)>=2000的前100个codeid 
按codeid ,sum(fq)输出. 也就是说,将首先满2000的前100个CODEID查询出来。

解决方案 »

  1.   

    没看懂, 什么叫 fid 升序 sum(fq)? 就是按fid 累加 fq? 累加到 2000 截止, 然后取前100个codeid?如果这样的话,  如果累加到 2000 了, 但没有100个codeid呢?
      

  2.   

    select 
      top 100 fid,sum(fq) 
    from 
      t1 
    group by 
      fid 
    having 
      sum(fq)>=2000 
    order by 
      fid,sum(fq) 
      

  3.   

    -- 如果是我描述的那种累加需求, 不足100的有多少取多少, 则用
    SELECT TOP 100
    *
    FROM(
    SELECT
    *,
    sum_fq = (SELECT SUM(fq) FROM t1 B WHERE A.fid >= B.fid)
    FROM t1 A
    )AA
    WHERE sum_fq <= 2000
    ORDER BY fid
      

  4.   

    --猜的
    select 
      top 100 distinct(fid)  
    from 
      t1 
    group by 
      fid 
    having 
      sum(fq)>=2000 
    order by 
      fid,sum(fq)
      

  5.   

    或者换个表达:
    table1,结构如下:codeid int,FQ decimal(18,2), fdate datetime(销售时间)这个表是记录每个销售员的销售记录,现在我需要奖励前100名首先销售额达10000的销售员,如果不够100,就将满足条件的那些查询出来。
      

  6.   

    select codeid,sum(fq) as total from t1
    group by codeid
    having sum(fq)>=2
      

  7.   


    select 
      top 100 fid,codeid,sum(fq)
    from 
      t1 
    group by 
      fid ,codeid
    having 
      sum(fq)>=2000 
    order by 
      fid,sum(fq)
      

  8.   

    加入codeid存的是销售员编号
    select 
      top 100 distinct(fid)  
    from 
      t1 
    group by 
      fid 
    having 
      sum(fq)>=2000 
    order by 
      fid,sum(fq)
      

  9.   

    select codeid,sum(FQ)
    from t1
    where codeid in (
    select top 100 codeid
    from t1 a
    where (select sum(FQ) from t1 where codeid=a.codeid and fid<=a.fid)>=2000
    and (select sum(FQ) from t1 where codeid=a.codeid and fid<a.fid)<2000
    order by fid)
    group by codeid