2016-11-24 27 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

相關問題