如何查询各个类别中选取几个记录;例如序号、姓名、职称
1、张三、高工
2、李四、高工
3、王五、高工
4、赵前、工程师
5、钱齐、工程师一条语句在高工、工程师中各选取一条,是否可以?

解决方案 »

  1.   

    declare @t table 
    (
    序号 int,姓名 varchar(10),职称 varchar(10)
    )
    insert @t select 1,'张三','高工'
    union all select 2,'李四','高工'
    union all select 3,'王五','高工'
    union all select 4,'赵钱','工程师'
    union all select 5,'钱齐','工程师'select * from @tselect * from @t t where not exists(select 序号 from @t where 职称=t.职称 and 姓名<t.姓名)
      

  2.   

    select a.* from tb a,
    (select 职称,min(序号) as 序号 from tb group by 职称) b
    where a.序号 = b.序号 and a.职称 = b.职称
      

  3.   


    create table T(序号 int, 姓名 varchar(20), 职称 varchar(20))
    insert T select 1,'张三','高工'
    union all select 2,'李四','高工'
    union all select 3,'王五','高工'
    union all select 4,'赵前','工程师'
    union all select 5,'钱齐','工程师'
    select * from T as tmp
    where(select count(*) from T where 职称=tmp.职称 and 序号<tmp.序号)<1--result
    序号          姓名                   职称                   
    ----------- -------------------- -------------------- 
    1           张三                   高工
    4           赵前                   工程师(2 row(s) affected)
      

  4.   

    if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb
    (
    序号 int,
    姓名 varchar(10),
    职称 varchar(10)
    )insert into tb(序号,姓名,职称) values(1,'张三','高工')
    insert into tb(序号,姓名,职称) values(2,'李四','高工')
    insert into tb(序号,姓名,职称) values(3,'王五','高工')
    insert into tb(序号,姓名,职称) values(4,'赵前','工程师')
    insert into tb(序号,姓名,职称) values(5,'钱齐','工程师')select a.* from tb a,
    (select 职称,min(序号) as 序号 from tb group by 职称) b
    where a.序号 = b.序号 and a.职称 = b.职称drop table tb--result
    序号        姓名       职称         
    ----------- ---------- ---------- 
    1           张三       高工
    4           赵前       工程师(所影响的行数为 2 行)