As I wrote, a naive solution would be to ... I can't think of any general purpose solution right now, but what about something like the following?
count(distinct REPLACE(b.id, '', '') || '' || REPLACE(b.name, '_', '')