HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Calculate amount of mugs StackExchange should give away so I'll receive one

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
awayamountgivereceiveonecalculatestackexchangeshouldmugs

Problem

Description

Calculate how many mugs StackExchange should give away(for graduation) to top reputed users on codereview.stackexchange.com so I'll also receive one. (output is divisible by 50).

Code

DECLARE @mugs INT,@rounded_mugs INT,@inc INT,@remainder INT;
SELECT  @mugs = COUNT(1) FROM Users WHERE Reputation >= 
  (SELECT Reputation FROM Users WHERE DisplayName='JaDogg');
SET  @remainder = @mugs%50;
IF (@remainder = 0) SET @inc = 0 ELSE SET @inc=50-@remainder; 
SELECT  @mugs+@inc AS 'AMOUNT OF MUGS TO GIVE AWAY';


Link

Calculate amount of mugs to give away so I'll receive one

Solution

Documentation

I think that what the query is doing is looking at your reputation rank, then rounding up to the nearest 50. It would be nice to hit "edit description" and document that for the benefit of anyone else using Stack Exchange Data Explorer.

Generality

Data Explorer allows parameterization. Use it.

Style

You shouldn't have to declare variables for such a simple query. In SQL, try to say what you want. Don't state the steps for calculating it.

A good way to avoid defining variables is to use Common Table Expressions (the WITH clause) instead.

Brevity

It would help to use the relevant functions RANK() and CEILING().

WITH UserRanks AS (
    SELECT DisplayName
         , RANK() OVER (ORDER BY Reputation DESC) AS RepRank
        FROM Users
)
SELECT *, 50 * CEILING((RepRank + 0.0) / 50) AS BatchedRepRank
    FROM UserRanks
    WHERE DisplayName = ##Username:string##;

Code Snippets

WITH UserRanks AS (
    SELECT DisplayName
         , RANK() OVER (ORDER BY Reputation DESC) AS RepRank
        FROM Users
)
SELECT *, 50 * CEILING((RepRank + 0.0) / 50) AS BatchedRepRank
    FROM UserRanks
    WHERE DisplayName = ##Username:string##;

Context

StackExchange Code Review Q#67703, answer score: 16

Revisions (0)

No revisions yet.