Count data value in a group from result set:
I have come up with a new scenario like, I need to add the data value in the result set.
Using the below technique, we can achieve the same.
create table venkattab (Number int,name1 varchar(10))
insert into venkattab values(1,'Venkat')
insert into venkattab values(2,'Venkat2')
Declare @SQLvar int
SET @SQLvar = 0
Select @SQLvar = @SQLvar + TempValue FROM
(Select Number as TempValue from venkattab where name1='Venkat'
Union All Select Number as TempValue from venkattab where name1='Venkat2')
AS A
Select @SQLvar -- Output is 3
Another Example,
Declare @SQLvar int
SET @SQLvar = 0
Select @SQLvar = @SQLvar + TempValue FROM ( Select 2 TempValue Union All Select 3 Union All Select 4) AS A
Select @SQLvar -- Output is 9
The query,
Select 2 TempValue Union All Select 3 Union All Select 4
will yield a result set 2,3,4 and the variable will fetch the summation of these values.
Happy Learning!!!
Regards,
Venkatesan Prabu . J
No comments:
Post a Comment