A phrase that is enclosed within double quote (") characters matches only rows that contain the phrase literally, as it was typed
... HAVING (COUNT(DISTINCT('sp.service_id'))) ...
json_encode работает вне while, но не работает внутри while.
НО, просто невозможно сделать так