Hi,
I have a piece of sql that composites data to a specified interval (@compositeby).
If I want to composite the data in the table by a float value (not an integer) then I get an error.
In the code below the @compositeby is set as 2.5, but it gives me an error:
Msg 245, Level 16, State 1, Line 6
Conversion failed when converting the varchar value '2.5' to data type int.
I have tried to declare the @compositeby as a float but it doesn't give the required results.
How do I fix this.
Thank you.
I have a piece of sql that composites data to a specified interval (@compositeby).
If I want to composite the data in the table by a float value (not an integer) then I get an error.
In the code below the @compositeby is set as 2.5, but it gives me an error:
Msg 245, Level 16, State 1, Line 6
Conversion failed when converting the varchar value '2.5' to data type int.
I have tried to declare the @compositeby as a float but it doesn't give the required results.
How do I fix this.
Thank you.
Code:
create table increment(id varchar(10),increment float,value float)
insert into increment(id,increment,value) values('1a','0.1','7')
insert into increment(id,increment,value) values('1a','0.5','4')
insert into increment(id,increment,value) values('1a','1','6')
insert into increment(id,increment,value) values('1a','1.5','2')
insert into increment(id,increment,value) values('1a','2','5')
insert into increment(id,increment,value) values('1a','2.5','8')
insert into increment(id,increment,value) values('1a','3','5')
insert into increment(id,increment,value) values('1a','3.5','1')
insert into increment(id,increment,value) values('1a','4','2')
insert into increment(id,increment,value) values('1a','4.5','3')
insert into increment(id,increment,value) values('1a','5','5')
insert into increment(id,increment,value) values('1a','5.5','4')
go
declare @compositeby varchar(30)
set @compositeby = 2.5
select id, inc_from, inc_to
, comp_val=(select sum(value) from increment where increment between tbl.inc_from and tbl.inc_to)/(select count(*) from increment where increment between tbl.inc_from and tbl.inc_to)
from
(select id
, inc_from=case when round(cast(increment as int)/@compositeby, 0)*@compositeby < (select min(increment) from increment) then (select min(increment) from increment) else round(cast(increment as int)/@compositeby, 0)*@compositeby end
, inc_to=case when round(cast(increment as int)/@compositeby, 0)*@compositeby + @compositeby > (select max(increment) from increment) then (select max(increment) from increment) else round(cast(increment as int)/@compositeby, 0)*@compositeby + @compositeby end
, value
from increment) tbl
group by id, inc_from, inc_to
drop table increment