Link to home
Start Free TrialLog in
Avatar of johnkainn
johnkainn

asked on

Calculate percentage

I have a table with the columns Id(int), Units(int), ItemId(int), MyText(string)
I want to find all "Units" with itemId=2 and add them all together. Then I want to find how many percent the Units in each row is of the total number and return as "UnitsPercentage".  How do I do that?

Example:
Row1:  Id=1, Units=2, ItemId=2, MyText="Blue"
Row2:  Id=2, Units=4, ItemId=2, MyText="Green"
Row3:  Id=3, Units=3, ItemId=2, MyText="Yellow"
Row4:  Id=4, Units=1, ItemId=2, MyText="Red"

Return:
Id=1, UnitsPercentage="20"
Id=2, UnitsPercentage="40"
Id=3, UnitsPercentage="30"
Id=4, UnitsPercentage="10"
Avatar of momi_sabag
momi_sabag
Flag of United States of America image

select distinct id, sum(units) over(partition by id) / count(*) over() as Unitspercentage
from myTable
ASKER CERTIFIED SOLUTION
Avatar of momi_sabag
momi_sabag
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial