可以把合条件的先查询出来
再查询时就将查询出来的这些优先排序

解决方案 »

  1.   

    我用product_id来定义排名,不用建立临时表,
    create table t(product_id int identity(1,1),[level] nvarchar(10))
    insert t select N'金牌'
    union all select N'银牌'
    union all select N'金牌'
    union all select N'金牌'
    union all select N'金牌'
    union all select N'银牌'
    union all select N'银牌'
    union all select N'普通'
    union all select N'普通'
    union all select N'铜牌'
    union all select N'铜牌'
    union all select N'银牌'select top 3 * from 
    (select product_id,[level],(select count(1) from t t2 where t2.product_id<=t1.product_id
    and t1.level=t2.level) as count from t t1) a where level=N'金牌' and [count]<=3
    union all
    select top 2 * from
    (select product_id,[level],(select count(1) from t t2 where t2.product_id<=t1.product_id
    and t1.level=t2.level) as count from t t1) a where level=N'银牌' and [count]<=2
    union all
    select top 1 * from
    (select product_id,[level],(select count(1) from t t2 where t2.product_id<=t1.product_id
    and t1.level=t2.level) as count from t t1) a where level=N'铜牌' and [count]<=1
    union all 
    select * from 
    (select product_id,[level],(select count(1) from t t2 where t2.product_id<=t1.product_id
    and t1.level=t2.level) as count from t t1) a where 
    (level=N'金牌' and [count]>3) or 
    (level=N'银牌' and [count]>2) or 
    (level=N'铜牌' and [count]>1)  drop table t
    /*
    product_id  level      count       
    ----------- ---------- ----------- 
    1           金牌         1
    3           金牌         2
    4           金牌         3
    2           银牌         1
    6           银牌         2
    10          铜牌         1
    5           金牌         4
    7           银牌         3
    11          铜牌         2
    12          银牌         4
    */
      

  2.   

    我用3条代表了你要的30条,以此类推。理解方法就好了。:)