select c.id,c.titolo as marca,g.gruppo,cc.categoria,case when c.id=64 then 1 else 0 end as selected from ( select distinct id_marca from articoli where disponibilita>0 and CHARINDEX(',3,', ',' + ISNULL(GruppiIN,'') + ',') > 0 and CHARINDEX(',505,', ',' + ISNULL(CategorieIN,'') + ',') > 0) a join marche c on a.id_marca=c.id join gruppi g on g.id_gruppo=3 join categorie cc on cc.id_categoria=505