一张news表,字段 id fid type
查询fid等于1,2,3,每个取5条,这五条中,type=1的1条,type=2的4条
不知道我说的大家能明白不- -!
select * from (select *,row_number() over(partition by fid,type order by id desc) as row from news )t
where t.fid in (1,2,3) and t.row<6
这条自己写sql语句 只是取到了 fid in(1,2,3)的各五条而已。我是sql新手,麻烦大家帮帮忙 谢谢!

解决方案 »

  1.   

    這樣?
    select * FROM (SELECT TOP 1 * FROM news WHERE Type=1 ORDER BY ID DESC)t
    UNION all
    SELECT TOP 4 * FROM news WHERE Type=2 ORDER BY ID desc
      

  2.   

    select * from (select *,row_number() over(partition by fid,type order by id desc) as row from news )t
    where t.fid in (1,2,3) and rn<=(case when type=1 then 1 when type=2 then 4 end)
      

  3.   

    select * from (select *,row_number() over(partition by fid,type order by id desc) as row from news 
    WHERE TYPE = 1
    )t
    where t.fid in (1,2,3) and t.row<2
    UNION ALL
    select * from (select *,row_number() over(partition by fid,type order by id desc) as row from news 
    WHERE TYPE = 2
    )t
    where t.fid in (1,2,3) and t.row<5
      

  4.   

    呵,你用的是row
     select * from (select *,row_number() over(partition by fid,type order by id desc) as row from news )t
    where t.fid in (1,2,3) and row<=(case when type=1 then 1 when type=2 then 4 end)
      

  5.   

    這樣試試
    select * 
    from (select *,row_number() over(partition by fid order by id desc) as row ,row_number() over(partition by fid,type order by id desc) as row2 from news )t
    where t.fid in (1,2,3) and t.row<6 AND(( type=1 AND row2=1)OR ( type=2 AND row2<5))
      

  6.   

    改改select * 
    from (select *,row_number() over(partition by fid,type order by id desc) as row from news )t
    where t.fid in (1,2,3) and (( type=1 AND row=1)OR ( type= AND row<5))