Q&A for professional and enthusiast programmers
-- Input a base tag. The query then finds the top 25 related
-- tags used with that base tag.
select TOP(50) t1.TagName as Tag, t2.TagName as "Related Tag", count(t2.TagName) as "Count"
from PostTags as pt1
INNER JOIN Tags as t1 ON pt1.TagId = t1.Id
INNER JOIN PostTags as pt2 ON pt1.PostId = pt2.PostId AND pt1.TagId <> pt2.TagId
INNER JOIN Tags as t2 ON pt2.TagId = t2.Id
INNER JOIN posts A on pt2.postid = A.id
where t1.TagName = ##MyTag:string##
-- and A.creationdate > getdate() - 365 Date filter
group by t1.TagName, t2.TagName
order by count(t2.TagName) desc