I was curious the how many people got the
before me - I am able to get this information
python 2019-01-02 09:09:15 Gold 454
with this (slow running) query:
(I was unable to single/cross login with my main user on data explorer, hence the anonymous login)
-- insert your user id here:
declare @uid int = 7505395
-- get all badges of all users
select Name, Date, [Gold/Silver/Else], [Row#] from (
SELECT Name,
Date,
userId,
case when class = 1 then 'Gold'
when class = 2 then 'Silver'
when class = 3 then 'Bronze'
else convert(varchar(10), class)
end as 'Gold/Silver/Else',
ROW_NUMBER() OVER(PARTITION BY name, class ORDER BY date ASC) AS Row#
FROM badges
WHERE 1 = 1
-- you can restrict this further, f.e. for looking only by gold badges
-- and Class = 1 -- gold == 1, silver == 2, bronze == 3
-- -- or for certain named badges
-- and name like 'python%'
) as tmp
where userID = @uid
ORDER by name asc, Date asc
(The query as is gives me all my badges with how many got it before me and has to sort through all possible badges)
Question:
I tried to CTE (only errors, did not work) and my sql skills are rusty - how to speedup this query?
The problem is that the Table does not seem to have indices that are useful for this. We get execution plans like:
-- Index scans are suboptimal. We want Index seeks.
Still, you can cut the time almost in half by:
Idas a proxy forDate. (Ids are unique, increasing, and often faster to sort.)Also note:
##UserId:INT##parameter.Classcolumn.ORDER BYclause.Anyway, this query performs better:
Update: This query performs even better because it aggregates multiply-earned badges: