数据表:db_id
字段:id char(10),code char(5)
要求是根据id排序,取code的前三个不重复值
sql:select TOP 3 code from db_id group by code order by id
报错信息:字段id不存在于聚合函数或group by条件中。求助 

解决方案 »

  1.   

    select top 3 code from(select district code from db_id ) as bb
    order by id
      

  2.   


    select top 3 code from db_id where not exists(select 1 from db_id where code = db_id.code and id > db_id.id)
      

  3.   

    select code from db_id t
    where not exists(select 1 from db_id where code=t.code and id<t.id)
      

  4.   

    select TOP 3 code from db_id group by code order by min(id)
      

  5.   

    select id,code from (select id,code,row_number() over(partition by code order by id) rn from db_id) a
    where a.rn<=3
      

  6.   

    上面写错了
    select top 3 code from(select distinct code from db_id ) as bb
    order by id 
      

  7.   

    select top 3 code from(select district code from db_id ) as bb
    order by id
      

  8.   


    WITH temp AS(
    SELECT ROW_NUMBER()OVER(PARTITION BY code ORDER BY ID DESC) AS rowId, ID, code 
    FROM dbo.[db_id])
    SELECT TOP(3) ID,CODE
    WHERE RowID =1
    ORDER BY ID DESC