Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL sum of rows

Tags:

sql

select

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)

like image 870
Surya Manne Avatar asked Feb 04 '13 09:02

Surya Manne


People also ask

Can you sum rows in SQL?

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.

How do you sum two rows in SQL?

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.

How do I sum all columns in SQL?

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.

How do you find the sum of a total in SQL?

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.


2 Answers

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
  • SQLFiddle Demo

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....

like image 164
John Woo Avatar answered Sep 22 '22 02:09

John Woo


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
like image 34
Kaf Avatar answered Sep 19 '22 02:09

Kaf