I have 300 records in my database and my structure is something like this
State values
Queensland 4554
Queensland 2343
Queensland 9890
NSW 1333
I want to retrieve all the records with state name Queensland
and I want to sum all the records with field name values and the sum to be divided with the number of records (count) with state name.
Can anybody help me out with the syntax to achieve this?
I need something the output to be 5595.66 (i.e. (4454+2343+9890)/3)
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.
SQL SUM() with where clause We can selectively find the sum of only those rows, which satisfy the given condition. To do this, we can use the where clause in the SQL statement.
The aggregate function SUM is ideal for computing the sum of a column's values. This function is used in a SELECT statement and takes the name of the column whose values you want to sum. If you do not specify any other columns in the SELECT statement, then the sum will be calculated for all records in the table.
Example 1: Using SUM() with One Column In this query, we use SUM() alone in the SELECT statement. The SUM() function adds all values from the quantity column and returns the total as the result of the function.
SELECT State, SUM(values) / (COUNT(*) * 1.0)
FROM tableName
WHERE State = 'Queensland'
GROUP BY State
OR
SELECT State, AVG(values * 1.0)
FROM tableName
WHERE State = 'Queensland'
GROUP BY State
As a sidenote, the columnName values
is a Reserved keyword. Escape it by a delimiter depending on the RDBMS you are using. Like (backtick) MySQL, (brackets) SQL Server, etc....
Based on
"I want to retrieve all the records with state name "Queensland".."
Are you looking for this (for SQL-Server) ? Fiddle-Demo
select [state], round(avg(value *1.0) over() ,2) avgValue
from T
where [state] ='Queensland'
--Results
state avgValue
Queensland 5595.67
Queensland 5595.67
Queensland 5595.67
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With