This is how I would write it. Using a WITH
block I would calculate the ROW_NUMBER
Over the counts using ROW_NUMBER
.
Note: this does not deal well with ties and will pull back arbitrary rows when they occur. You could use RANK
if you want to show more than two hashtags in this case
with TopTwoHashtags
AS (
SELECT
t.userID,
th.HASHTAGID,
ROW_NUMBER() OVER (ORDER BY COUNT(th.TWEETID) DESC) r
FROM
Tweet_Hashtag th
INNER JOIN Tweets t
ON th.TWEETID = t.TWEETID
WHERE
userID = 3
GROUP BY
t.userID,
th.HASHTAGID
)
SELECT
ht.TOPIC
FROM
Hashtag ht
INNER JOIN TopTwoHashtags tt
ON ht.HASHTAGID = tt.HASHTAGID
WHERE
r < 3;