2016-11-24 4 views
0

Ich habe eine Abfrage wie dieseWie bekomme ich einen Status für die erste "n" Anzahl von Zeilen für bestimmte Bedingungen?

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 

Die Abfrage Rückkehr 1000s Zeilen, würde Ich mag res Spalte als 1 für die ersten 100 Zeilen mit Bedingung AppStatusId = 80. Ich erwarte folgendes Ergebnis

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) 
erhalten

Antwort

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 

Dies sollte Sie dorthin bringen. Es erzeugt eine Zeilennummer, die nur erhöht wird, wenn plus es Ihnen erlaubt, eine beliebige Reihenfolge der Datensätze auszuwählen, so dass die ersten 100 Datensätze AppStatusId = 80 nicht fortlaufend sein müssen, wenn Sie nicht möchten, dass sie sind. Wenn Sie einfach so bestellen und es wird immer noch funktionieren.

+0

erinnern Sie sich, alias die Unterabfrage;) –

+1

dies auch 'CROSS JOIN (SELECT @rn: = 0)' –

+0

@JuanCarlosOropeza duh ja danke gefangen, während Sie tippten. Vielen Dank! – Matt

Verwandte Themen