===== 未完,按错键了假如有表如下:
  code,name
   001   aa
   002   bb
   001   cc
   002   dd
   002   ee
   003   ff  ...
请问如何根据如下的指定表得到相关记录
   code  cnt  
    001   2
    002   3
    003   1
即:编码为001的取前2条记录,002的取前3条记录 ....

解决方案 »

  1.   

    select  
        code,
        cnt=count(*)
    from 表
    group by  code
      

  2.   

    你搞错我的意思了
    我要的是 select top n * from table 类似的语句,
    但 这里的n 是根据表2中的cnts变化的
      

  3.   

    --用动态SQL解决!
    exec( 'select top '+@n+' * from table ')
      

  4.   

    我也想过了,可就是不知道如何能用一条语句实现!
     烦请  zlp321002(好好学习,贴贴向上) 
     详细告知,多谢了
      

  5.   

    --类似如下:
    --建测试环境
    Create table T1 ( code varchar(10),name varchar(10))
    insert into T1 select '001','aa'
    union all select '002','bb'
    union all select '001','cc'
    union all select '002','dd'
    union all select '002','ee'
    union all select '003','ff'
    goCreate table T2(code varchar(10),cnt int)
    insert into T2 select '001',2
    union all select '002',3
    union all select '003',1
    go
    --动态SQLdeclare @val varchar(10),@i int
    set @val='001'
    select @i=cnt from T2 where code=@val
    exec( 'select top '+@i+' * from T1 ')--结果code       name       
    ---------- ---------- 
    001        aa
    002        bb--删除测试环境
    Drop table T1,T2--或者把动态SQL 封装成存储过程,通过存储过程处理。
      

  6.   

    动态sql可以,在yukon中支持参数定义top n
      

  7.   

    --用动态SQL解决!
    exec( 'select top '+@n+' * from table ')
    可以