t-SQL Calculate Percentage

declare @Product table
 (
     ProductID int,
     Color varchar(5)
)
insert into @Product
     select 1, 'Black' union all
     select 2, 'Red' union all
     select 3, 'Blue' union all
     select 4, 'Black' union all
     select 5, 'Black' union all
     select 6, 'Red' union all
     select 7, 'Grey' union all
     select 8, 'Red' union all
     select 9, 'Blue'

SELECT Color, (COUNT(*)*1.0)/COUNT(*) OVER() AS PercentColor 
FROM @Product 
GROUP BY Color

Output:

Color   PercentColor
-----  -----------------------
Black  0.750000000000
Blue   0.500000000000
Grey   0.250000000000
Red    0.750000000000
Advertisements
By simplemsexchange Posted in SQL 2008

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s