Users with most marshal badges, network-wide

1

Please login or register to vote for this query.

(click on this box to dismiss)

I am the second on the whole network!

Stack Overflow

Q&A for professional and enthusiast programmers

DECLARE @output TABLE (
  DbName VARCHAR(max),
  UserName VARCHAR(max),
  AccountId INT,
  N INT);

DECLARE @query VARCHAR(MAX);

DECLARE dbcursor CURSOR FOR
SELECT name
FROM sysdatabases
WHERE name NOT IN ('master', 'tempdb', 'model' ,'msdb', 'Data.StackExchange')

DECLARE @dbname VARCHAR(max);

OPEN dbcursor;
FETCH NEXT FROM dbcursor INTO @dbname;

WHILE @@FETCH_STATUS = 0
BEGIN
  SELECT @query = '
    SELECT
      ''' + @dbname + ''' AS DbName,
      MIN(Users.DisplayName) AS UserName,
      MIN(Users.AccountId) AS AccountId,
      COUNT(*) AS N
    FROM [' + @dbname + '].dbo.Users
    LEFT JOIN [' + @dbname + '].dbo.Badges ON Badges.UserId = Users.Id
    WHERE Badges.Name = ''Marshal''
    GROUP BY Users.Id';
  INSERT INTO @output EXEC (@query);
  FETCH NEXT FROM dbcursor INTO @dbname;
END

CLOSE dbcursor;

WITH Combined AS (
  SELECT
    MIN(UserName) AS UserName,
    AccountId,
    SUM(N) AS N
  FROM @output
  GROUP BY AccountId
)
SELECT
  DENSE_RANK() OVER (ORDER BY N DESC) AS Rank,
  'http://stackexchange.com/users/'
    + CAST(AccountId AS VARCHAR(30))
    + '?tab=accounts|' + UserName AS 'SE Account',
  'https://data.stackexchange.com/stackoverflow/query/678540?AccountId='
    + CAST(AccountId AS VARCHAR(30)) + '#resultSets|' + UserName
    AS [With Hidden Accounts],
  N AS StewardBadges
FROM Combined
ORDER BY N DESC, AccountId;

Enter Parameters

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