Challenges

  • + 0 comments

    Brother, you and I are totally on the same page. I learned a ton, and since I never check the Discussions until I write successful code (at least on my tsql testbed), I was excited to see my own MS SQL code was nearly identical to yours in terms of logic, and I literally spent DAYS racking my brain around this, so seeing it was a huge relief.

    Funny thing is, when I succeeded, I added comment lines to the code in my own notes with very similar commentary as yours. LOL!

    (Note: Some of my code might have one or two redundant/extraneous items in the subqueries, as I would run my subqueries independently for visualization purposes prior to adding them to my main query, and so may have forgotten to remove extraneous subquery columns.)

    /* select the desired columns from the two tables */
    SELECT h.hacker_id, h.name, count(c.hacker_id)
    FROM hackers h
    JOIN challenges c ON h.hacker_id = c.hacker_id
    GROUP BY h.hacker_id,h.name
    
    /* check for rows matching the max poss score */
    HAVING count(c.hacker_id) = (
        SELECT max(n.num) FROM (
            SELECT hacker_id, count(hacker_id) num
            FROM challenges
            GROUP BY hacker_id) n)
    
    /* check for rows that match only distinct scores */
    OR count(c.hacker_id) IN (
        SELECT w.num FROM (
            SELECT count(c.hacker_id) num
            FROM challenges c
            GROUP BY c.hacker_id) w
        GROUP BY w.num
        HAVING count(w.num) = 1)
    
    /* order the results as directed */		
    ORDER BY count(c.hacker_id) desc, h.hacker_id;
    

    Side note: I'm not sure why, but for some reason I could not rename the original count(hacker_id) with an "AS c_count" alias like you did (in my case I wanted to use "numchal" for "number of challenges submitted"). When I would try to call back to it, I would get an error saying the column didn't exist (and obviously it did), or that I was trying to use it illegally in another aggregate function. I could only call aliases like that when they were defined in another table or subquery. Maybe that's a quirk of psql/PostGreSQL/pgAdmin?