Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,
I have a problem with select query.
SQL
How to get average in sqlserver select query, column type is nvarchar.

In my reviews table rating column is nvarchar. but I inserted integer values. Now I want average of total rating.
SELECT AVG(Rating) AS rating FROM CompanyReviews;

Please give me the soluation.

Thank you.
Posted
Comments
Maciej Los 21-May-14 3:12am    
Bad table design! Bad practice!

AVG(Cast(Rating as INT)) as avg_Rating
 
Share this answer
 
Comments
NagaRaju Pesarlanka 21-May-14 3:12am    
Thank you.
I got answere.
I am using like this query
SELECT AVG(CAST(Rating as decimal(10,2))) AS rating FROM CompanyReviews
3.202127
but I want 2 digits only after decimal.
King Fisher 21-May-14 3:22am    
again cast it.
SELECT cast((AVG(CAST(Rating as float))) as decimal(10,2)) AS rating FROM CompanyReviews

better you could change datatype .
NagaRaju Pesarlanka 21-May-14 3:25am    
yes, I got the answere from your query.
Thank you
Please read my comment to the question.

If you want to store numeric data, use numeric field instead of nvarchar. I'd strongly recommend to redesign your table.

To convert data between varchar and numeric data types, use CAST or CONVERT function[^].
 
Share this answer
 
SELECT AVG(CAST(Rating AS INT)) FROM CompanyReviews
 
Share this answer
 
Comments
NagaRaju Pesarlanka 21-May-14 3:19am    
Thank you.
I got answere.
I am using like this query
SELECT AVG(CAST(Rating as decimal(10,2))) AS rating FROM CompanyReviews
3.202127
but I want 2 digits only after decimal.
You can get the average by doing cast to decimal type

SELECT AVG(CAST(Rating AS DECIMAL)) AS rating FROM CompanyReviews

Regards,
AK
 
Share this answer
 
Comments
NagaRaju Pesarlanka 21-May-14 3:19am    
Thank you.
I got answere.
I am using like this query
SELECT AVG(CAST(Rating as decimal(10,2))) AS rating FROM CompanyReviews
3.202127
but I want 2 digits only after decimal.
try this.. :)

SQL
SELECT AVG(convert(int,Rating)) AS rating FROM CompanyReviews;


or

SQL
SELECT AVG(cast(Rating as int)) AS rating FROM CompanyReviews;
 
Share this answer
 
Comments
NagaRaju Pesarlanka 21-May-14 3:20am    
Thank you.
I got answere.
I am using like this query
SELECT AVG(CAST(Rating as decimal(10,2))) AS rating FROM CompanyReviews
3.202127
but I want 2 digits only after decimal.
SELECT AVG(Cast(Rating As Decimal(18,6))) AS rating FROM CompanyReviews
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900