Skip to content
Advertisement

Reading 0.5 value in ROW_NUMBER() and PARTITION BY | SQL Server 2012

I have this question before Looping between 2 case parameters (Date Range and Row Count) | SQL Server 2012 , now I’m thinking about a scenario, what if the value has a 0.5? or .5? Will this work using ROW_NUMBER()?

I’m trying to make this work using only CASE method.

This is my old script:

This is the output:

enter image description here

This is my expected output:

enter image description here

Is there a way for this to work? Thank you.

Advertisement

Answer

You can greatly simplify your query by noting that VAL.NUMBER is already your row number (just starting at 0 instead of 1). You can then compare your Count value to VAL.NUMBER and if Count - VAL.NUMBER is greater than 1, output 1; if it’s greater than 0 output the difference, otherwise output NULL. For this demo query I’ve simulated your numbers table with a table value constructor:

Output:

Demo on dbfiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement