Top N users for tag located in city / country (for answers)

3

Please login or register to vote for this query.

(click on this box to dismiss)

Select top N users by upvotes they received for their answers for a given tag located in the specified city or country

Science Fiction and Fantasy

Q&A for science fiction and fantasy enthusiasts

-- Top N users for tag in city / country
-- Created by Mihai Todor (http://stackoverflow.com/users/1174378/mihai-todor)

/*
Usage:
Tag - tag name (mandatory)
Country, City - specify either one but not both (they will be concatenated into Location)
NoResults - number of desired results
*/

DECLARE @Tag NVARCHAR(35) = ##Tag:string##;
DECLARE @Location NVARCHAR(100) = LTRIM(RTRIM(##City:string? ##)) + LTRIM(RTRIM(##Country:string? ##));
DECLARE @NoResults INT = ##NoResults?10##;
--DECLARE @IncludeEditors BIT = ##IncludeEditors?0##;--boolean (0 or 1; default 0)

SELECT TOP (@NoResults)
  ROW_NUMBER() OVER(ORDER BY Reputation DESC) AS [#],
  u.Id AS [User Link],
  SUM(a.Score) AS [Tag Score],
  u.Reputation
FROM Posts AS p
INNER JOIN Posts AS a ON a.ParentId = p.id -- answers only
INNER JOIN PostTags AS pt ON p.Id = pt.PostId
INNER JOIN Tags AS t ON pt.TagId = t.Id
INNER JOIN Users AS u ON u.Id = a.OwnerUserId
  -- OR (u.Id = a.LastEditorUserId AND @IncludeEditors = 1)
WHERE a.PostTypeId = 2 -- answers only
AND t.TagName IN (
  SELECT @Tag
  UNION
  SELECT SourceTagName FROM TagSynonyms WHERE LOWER(SourceTagName) LIKE LOWER('%' + @Tag + '%')
  UNION
  SELECT TargetTagName FROM TagSynonyms WHERE LOWER(TargetTagName) LIKE LOWER('%' + @Tag + '%')
)
AND (
  LOWER(u.Location) LIKE LOWER('%' + @Location + '%')
  OR
  LOWER(u.AboutMe) LIKE LOWER('%' + @Location + '%')
)
GROUP BY u.Id, u.Reputation
ORDER BY SUM(a.Score) DESC

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results