How do I retrieve decimals when rounding an average in SQL
Im not sure if this will help you skullomania but try this
SELECT CAST(AVG(CAST(column_name as DECIMAL(10,2))) AS DECIMAL(10,2))FROM [table_name]
The float is an approximate, The decimal on the other hand will make it more of an exact, you may want to read up on floats math and decimals. I struggled at first with this and still feel lost at times. Hopefully this will help you out.
IN C#
not sure if I can get in trouble for posting the answer here but have you tried converting it to a double and using a ExecuteScalar()
try this:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn= sqlconnectionstring;
SqlCommand cmd = new SQLCommand("SELECT STATEMENT",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
Double result = Convert.ToDouble(cmd.ExecuteScalar());
lblresult.text = "the result is " + result;
conn.Dispose();
cmd.Dispose();
}
You don't even need to do a ROUND
there, really. You could just convert your values to DECIMAL
, like this:
SELECT AVG(CONVERT(DECIMAL(16,2),YourColumn))
FROM YourTable
The average will have the same data type as the values, so cast the values:
SELECT ROUND(AVG(CAST(column_name AS FLOAT)), 2) FROM [database].[dbo].[table]