How many times has the tag been added/removed

1

Please login or register to vote for this query.

(click on this box to dismiss)

Super User

Q&A for computer enthusiasts and power users

--this query misses some tags additions and removals
--if the tag was added and removed in the same posts several times
--in deleted posts (they are not present in the PostHistoryTable)

SELECT
ph1.PostId AS pid, Min(ph1.Id) AS phWithId, Min(ph1.Id) as MaxWithTag
INTO #firstwithtag_cte
FROM PostHistory ph1 
WHERE ph1.PostHistoryTypeId in (3,6,9)
  and ph1.Text Like '%<##tagName##>%'
GROUP BY ph1.PostId

go

/*
;  with firstwithtag_cte as
(
SELECT
p.Id AS pid, Min(ph1.Id) AS phWithId, Min(ph1.Id) as MaxWithTag
FROM PostHistory ph1 INNER JOIN Posts p ON ph1.PostId=p.Id
WHERE ph1.PostHistoryTypeId in (3,6,9)
  and ph1.Text Like '%<##tagName##>%'
GROUP BY p.Id
),*/


SELECT
  pid, phWithId, MIN(ph2.Id) as phWithoutId
--phWithoutId is the PostHistory.Id for the LAST removal of the tag from the post with Post.Id=pid
  INTO #firstwithouttag_cte
  FROM #firstwithtag_cte INNER JOIN PostHistory ph2 ON ph2.PostId=pid
  WHERE (ph2.Id>MaxWithTag)
   AND ph2.PostHistoryTypeId in (3,6,9)
   AND NOT(ph2.Text Like '%<##tagName##>%')
GROUP BY pid, phWithId

go

/*
;with firstwithouttag_cte as
(SELECT
  pid, phWithId, MIN(ph2.Id) as phWithoutId
--phWithoutId is the PostHistory.Id for the LAST removal of the tag from the post with Post.Id=pid
FROM #firstwithtag_cte INNER JOIN PostHistory ph2 ON ph2.PostId=pid
  WHERE (ph2.Id>MaxWithTag)
   AND ph2.PostHistoryTypeId in (3,6,9)
   AND NOT(ph2.Text Like '%<##tagName##>%')
GROUP BY pid, phWithId
),*/
; with datesaddedremoved_cte as
(
SELECT pid, ph1.CreationDate as FirstAddedDate, ph2.CreationDate as LastRemovedDate
FROM #firstwithouttag_cte INNER JOIN PostHistory ph1 ON ph1.Id=phWithId
  INNER JOIN PostHistory ph2 ON ph2.Id=phWithoutId
),
countsaddedbefore_cte AS
(SELECT
  COUNT(d2.FirstAddedDate) AS CountAddedBefore, d1.LastRemovedDate AS rDate
FROM datesaddedremoved_cte d1 INNER JOIN datesaddedremoved_cte d2 ON (d2.FirstAddedDate<=d1.LastRemovedDate)
GROUP BY d1.LastRemovedDate
),
countsremovedbefore_cte AS
(SELECT
  COUNT(d2.LastRemovedDate) AS CountRemovedBefore, d1.LastRemovedDate AS rDate
FROM datesaddedremoved_cte d1 INNER JOIN datesaddedremoved_cte d2 ON (d2.LastRemovedDate<=d1.LastRemovedDate)
GROUP BY d1.LastRemovedDate
),
counts_cte AS
(SELECT
  d1.pid AS pid, d1.LastRemovedDate AS rDate, c1.CountAddedBefore AS CountAddedBefore, c2.CountRemovedBefore AS CountRemovedBefore
FROM datesaddedremoved_cte d1 INNER JOIN countsaddedbefore_cte c1 ON (d1.LastRemovedDate=c1.rDate)
  INNER JOIN countsremovedbefore_cte c2 ON (d1.LastRemovedDate=c2.RDate)
)

SELECT
  pid AS [Post Link],
  url = 'site://posts/' + CAST(pid AS varchar)+'/revisions',
  rDate AS [DateRemoved]
FROM counts_cte
WHERE (CountAddedBefore=CountRemovedBefore)
ORDER BY rDate ASC

Enter Parameters

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