SELECT wt, ht, ag , CASE WHEN c1 + c2 + c3 > 1 THEN 4 WHEN c1 = 1 THEN 1 WHEN c2 = 1 THEN 2 WHEN c3 = 1 THEN 3 ELSE 0 END flag FROM (SELECT wt, ht, ag , CASE WHEN wt >= 100 AND ht >= 100 THEN 1 ELSE 0 END c1 , CASE WHEN ag <= 20 AND ht >= 100 THEN 1 ELSE 0 END c2 , CASE WHEN ag >= 20 AND wt >= 20 THEN 1 ELSE 0 END c3 FROM t ) a ;