Update:
Worked this out myself now. Here is the final badge query:
WITH unpinned AS ( /* Get eligible topics posts with at least one pinned.disabled */
SELECT t.user_id, t.id
FROM badge_posts p
INNER JOIN topics t on t.id = p.topic_id
WHERE p.action_code ilike 'pinned.disabled'
GROUP BY t.id, t.user_id
HAVING count(*) > 0
)
SELECT user_id, count(*), current_timestamp granted_at
FROM unpinned
GROUP BY user_id
HAVING count(*) > 0
The last count must be changed to the number of topics that once have been pinned e.g. >0 = at least one pinned topic, >10 at least 10 once pinned topics.
I had to go with the pinned.disabled workaround as Discourse does not have any other data point about pin histories available in the database. Also it is not possible to distinct this query between regular pins and global pins due to the lack of available data.
This should be changed going forward IMHO, as global pin > regular pin > comments > likes > views for engagement statistics in my opinion, but they are not accounted for at all.