Search code examples
sqlt-sqlcursor

How can I efficiently run through this data?


I need to find the average values of col2, based on col1. Currently I have a cursor to run through the data, but it's extremely inefficient and I'm not sure how to effectively use a while loop to run through the data. Here is the first part of the data:

Col1      Col2   
2           12  
2           43  
2           49  
2           51  
3           51  
3           49  
3           43  
3           12  
5           12  
5           12  
5           43  
5           49  
5           51  
6           51  
6           49  
6           43  
6           12  
7           12  
7           12  
7           43  
7           51  
7           49  

Column 1 should not have any repeat values after the query is done. The idea is to just average out all the numbers in col2 using col1 as a guide.


Solution

  • You could use avg and group by

      select col1, avg(col2)
      from my_table 
      group by col1