2016-11-24 84 views
0

我有这样如何获得第一个“n”行数的某些状态,特别是条件?

SELECT DISTINCT Id, AppStatusId, 
IF ((AppStatusId = 80),"1","2") as res 
#(here i need res as "1" if AppStatusId = 80 for first 100 rows ) 
FROM App 
WHERE 
AppStatusId = 80 
or 
AppTypeId = 100 

行的查询返回1000查询,我想获得RES列1为前100行与条件AppStatusId = 80.我期待以下结果

Id, AppStatusId,res 
14343 ,80 , ,1 
2234 ,80 , ,1 
3232 ,80 , ,1 
.................. 
.................. 
.................. 
.................. 
8975, 80,  ,1 # 100th row 
3232, 80,  ,0 
102, 80,  ,0 
103, 80,  ,0 
.................. 
.................. 
222, 55,  ,0 (becuase of or AppTypeId = 100 in where condition) 

回答

0
SELECT 
    Id 
    ,AppStatusId 
    ,if(AppStatusId = 80 AND RowNumber <= 100, 1, 0) as res 
FROM 
    (
     SELECT 
      * 
      ,(@rn:= if(AppStatusId = 80, @rn + 1,@rn)) as RowNumber 
     FROM 
      App a 
      CROSS JOIN (SELECT @rn:=0) var 
     WHERE 
      a.AppStatusId = 80 
      OR a.AppTypeId = 100 
     ORDER BY 
      Id, AppstatusId...., whatever you want for the first 100 records 
    ) t 

这应该让你在那里。它生成的行号只有在AppStatusId = 80加上时才会增加,它允许您选择记录的任何顺序,因此如果不希望它们成为AppStatusId = 80,那么AppStatusId = 80不必是连续的。如果你只是这样订购,它仍然会工作。

+0

记得你必须别名子查询;) –

+1

这也是'CROSS JOIN(SELECT @rn = 0)' –

+0

@JuanCarlosOropeza是的,谢谢你在打字的时候发现了。谢谢! – Matt

相关问题