开发者

T-SQL average rounded to the closest integer

I'm not sure if this has been asked before, but how do I get the aver开发者_高级运维age rounded to the closest integer in T-SQL?


This should do it. You might need a GROUP BY on the End depending on what you are looking for the average of.

SELECT CONVERT(int,ROUND(AVG(ColumnName),0))
FROM 
TableName

EDIT: This question is more interesting than I first thought.

If we set up a dummy table like so...

WITH CTE

AS

(
    SELECT 3 AS Rating
    UNION SELECT 4
    UNION SELECT 7
)


SELECT AVG(Rating)
FROM 
CTE

We get an integer average of 4

However if we do this

WITH CTE

AS

(
    SELECT 3.0 AS Rating
    UNION SELECT 4.0
    UNION SELECT 7.0
)


SELECT AVG(Rating)
FROM 
CTE

We get a decimal average of 4.666..etc

So it looks like the way to go is

WITH CTE

AS

(
    SELECT 3 AS Rating
    UNION SELECT 4
    UNION SELECT 7
)
SELECT CONVERT(int,ROUND(AVG(CONVERT(decimal,Rating)),0))
FROM CTE

Which will return an integer value of 5 which is what you are looking for.


If you are in SQL Server, just use round(avg(column * 1.0), 0).

The reason for * 1.0 is because sql server in some cases returns calculations using the same datatype of the values used in the calculation. So, if you calculate the average of 3, 4 and 4, the result is 3.66..., but the datatype of the result is integer, therefore the sql server will truncate 3.66... to 3, using * 1.0 implicit convert the input to a decimal.

Alternatively, you can convert or cast the values before the average calculation, like cast(column as decimal) instead of using the * 1.0 trick.

If your column it's not a integer column, you can remove the * 1.0.

PS: the result of round(avg(column * 1.0), 0) still is a decimal, you can explicit convert it using convert(int, round(avg(column * 1.0), 0), 0) or just let whatever language you are using do the job (it's a implicit conversion)


Select cast(AVG(columnname) as integer)


This worked for it:

CONVERT(int,ROUND(AVG(CAST(COLUMN-NAME AS DECIMAL)) ,0))

Isn't there a shorter way of doing it though?


T-SQL2018.

CAST(ROUND(COLUMN, 0) AS INT) This code does the job for me and gives the output I require so a 4.8 becomes 5.

whereas

CAST(AVG(COLUMN) AS INT) This code almost does the job but rounds down, so 4.8 becomes a 4 and not 5.


select cast(avg(a+.5) as int) from 
    (select 1 a union all select 2) b

If you don't like shortcuts, you could use the long way:

select round(avg(cast(a as real)), 0) 
    from (select 1 a union all select 2) b


The following statements are equivalent:

-- the original code
CONVERT(int, ROUND(AVG(CAST(mycolumn AS DECIMAL)) ,0))

-- using '1e0 * column' implicitly converts mycolumn value to float
CONVERT(int, ROUND(AVG(1e0 * mycolumn) ,0))

-- the conversion to INT already rounds the value
CONVERT(INT, AVG(1e0 * mycolumn))


On SQL 2014,

select round(94,-1)
select round(95,-1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜