Networkwide questions per account, ordered by view count

0

Please login or register to vote for this query.

(click on this box to dismiss)

Open Source Meta

Q&A about the site for people organizing, marketing or licensing open source development projects

-- result table, don't rename and keep the site column
create table #results (site nvarchar(250), id int, title nvarchar(250)
                       , viewcount int, score int, favoritecount int, createddate datetime);

declare @sql nvarchar(max) = ''   -- holds build up sql string

-- build one biq union sql, for each db
select @sql = @sql 
+ iif( len(@sql) > 1 
     , 'union all'
     , 'insert into #results'
) +
-- here goes the per site query, fully qualify the database objects
N'
select ''' + name + '''
     , p.id, p.title, p.viewcount, p.score, p.favoritecount, p.creationdate
from ' + quotename(name) + '.dbo.posts as p
inner join ' + quotename(name) + '.dbo.users as u on p.owneruserid = u.id
where p.posttypeid = 1 and u.accountid = ' + CAST(##AccountId:int## AS nvarchar) + ''
from sys.databases
where database_id > 5
-- and (name not like '%.Meta' or name = 'StackExchange.Meta')

--print @sql

-- execute it
exec (@sql)

-- Site details, cf. https://meta.stackexchange.com/a/359795/295232
CREATE TABLE #Sites (URL NVARCHAR(100), SiteName NVARCHAR(100), DatabaseName NVARCHAR(50));
-- fetch Markdown for post containing table with site details
DECLARE @md NVARCHAR(MAX);
SELECT TOP 1 @md = Text
  FROM [StackExchange.Meta].dbo.PostHistory
  WHERE PostId = 359796 AND PostHistoryTypeId = 5
  ORDER BY CreationDate DESC;
-- split Markdown on pipe symbol
CREATE TABLE #TableEntries (ID INT IDENTITY(1, 1), Value NVARCHAR(100));
INSERT INTO #TableEntries (Value)
SELECT LEFT(TRIM(VALUE), 100) FROM STRING_SPLIT(@md, '|')
  WHERE LEN(TRIM(REPLACE(REPLACE(VALUE, CHAR(10), ''), CHAR(13), ''))) > 0;
-- 'pivot' - we have to discard the introductory text, headers and horizontal lines
INSERT INTO #Sites
SELECT t0.Value, t1.Value, t2.Value
  FROM #TableEntries AS t0
  INNER JOIN #TableEntries AS t1
    ON t0.Id + 1 = t1.Id
  INNER JOIN #TableEntries AS t2
    ON t0.Id + 2 = t2.Id
  WHERE t0.Id >= 8 -- that's where the real content starts
    AND t0.Id % 3 = 2;

-- show results
select SiteName AS 'site'
   , URL + '/q/' + CAST(id AS nvarchar) + '|' + title AS 'question'
   , viewcount AS '# views'
   , score
   , favoritecount AS '# fav'
   , createddate AS 'posted on'
  FROM #Results AS r
  INNER JOIN #Sites AS s
    ON r.Site = s.DatabaseName
  order by viewcount desc

drop table #results

Enter Parameters

Options:
Switch to main site
loading Hold tight while we fetch your results