sql server - Return difference of comparing percentage value of a column -
i have colum 10,000 finincial records. values are: id pk, owingvalue
example data
id owingvalue 1 123.2 2 123.4 3 123.5 4 123.6 5 123.7 6 140.2 7 140.3
for giving column more 0.7% difference previous record, return records high difference.
in case result column 7 because (column 6 owingvalue - column 5 owingvalue) multiply 100 give 1.650 percent higher our threshold of 0.7% need sql while loop or curso me solve problem.
thanks in advance
try this:
declare @t table ( id int, v money ) insert @t values ( 1, 123.2 ), ( 2, 123.4 ), ( 3, 123.5 ), ( 4, 123.6 ), ( 5, 123.7 ), ( 6, 140.2 ), ( 7, 140.3 ) select t1.id @t t1 join @t t2 on t1.id = t2.id + 1 join @t t3 on t2.id = t3.id + 1 ( t2.v - t3.v ) / t3.v * 100 > 0.7
output:
id 7
if ids have gaps then:
declare @t table ( id int, v money ) insert @t values ( 1, 123.2 ), ( 2, 123.4 ), ( 3, 123.5 ), ( 5, 123.6 ), ( 9, 123.7 ), ( 16, 140.2 ), ( 27, 140.3 ); cte ( select row_number() on ( order id ) id , v @t ) select t1.id cte t1 join cte t2 on t1.id = t2.id + 1 join cte t3 on t2.id = t3.id + 1 ( t2.v - t3.v ) / t3.v * 100 > 0.7
Comments
Post a Comment