SELECT p.* FROM dev1.ds_products as p, ds_product_categories as c, ds_product_option_sets as d where (p.invLevel > 0 or (p.invTrack = 'O' and d.inventory > 0)) and p.pID = d.productId and p.pID = c.pID and c.catID !=0 and p.pAvail = 'Y' and ( p.venID = '24' ) group by p.pID order by case c.sortOrder when 0 then 100 else c.sortOrder end