Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of grouped rows in Sql Server

I have an Sql Server Table.. it's something like this:

Id ...... Column1 ...... Column2  
````````````````````````````````  
1 ........ 1 ............. 34  
2 ........ 1 ............. 44  
3 ........ 2 ............. 45  
4 ........ 2 ............. 36  
5 ........ 2 ............. 23  
6 ........ 3 ............. 68  
7 ........ 3 ............. 26  

So, I need to select the average of Column2,but group with column1 before doing that.
I mean, if I say Avg(Column2) it just returns a single row with the average of all rows.

What I need is, first i need to group them by column so:
Average of column2 where column1 = 1
Average of column2 where column1 = 2
Average of column2 where column1 = 3

So I want 3 rows returned with the averages of respective values of column1. I am lost at doing this, any hints / help please?

ps: I tried several related questions, and none of them helped / I couldn't understand.

like image 822
iamserious Avatar asked Jun 23 '10 10:06

iamserious


People also ask

How do you find the average of specific rows in SQL?

The AVG function finds the arithmetic mean for a group of records in a SQL table. An average, or arithmetic mean, is the sum of a group of numbers divided by the count for that group. For example, 2+4+4+6+6+8 is 30 divided 6 which results in an average of 5.

How do you find the average of a group in SQL?

SQL Server AVG() function is an aggregate function that returns the average value of a group. In this syntax: ALL instructs the AVG() function to take all values for calculation. ALL is used by default.

What does AVG () do in SQL?

The AVG() function returns the average value of a numeric column.

How do I count rows in SQL by group?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.


2 Answers

Is this what you want?

select column1, avg(column2) from table group by column1
like image 69
Blorgbeard Avatar answered Sep 22 '22 04:09

Blorgbeard


simple

select AVG(Column2) from table group by Column1

doesn't work?

like image 23
nothrow Avatar answered Sep 20 '22 04:09

nothrow