Friday, June 15, 2012

using SQL for sums and averages

Using the table and its data as shown here I can run the following commands to get sums and averages off of the DataPoint column which contains decimal values. Observe:

SELECT SUM(DataPoint) AS SumOfData FROM [AAC\vafscjaesct].Whatever

 
 

The above SQL returns 58. This is a sum of all 12 rows. An average of 4.833333 (again across all 12 rows) is brought back from this query:

SELECT AVG(DataPoint) AS AvgOfData FROM [AAC\vafscjaesct].Whatever

 
 

What if we wish to get separate sums and averages for separate chunks of the dozen rows? The following two queries show how that is done and also the table that comes back in each case detailing the breakdown. The rows are categorized based upon the SomethingElse column in this example. Imagine how something comparable might be done for a view "over top" of a table. One could have the line items of orders for a shopping cart in a table and then order summaries for the individual orders summarized in a view. In this scenario, the line item price values could be summed and grouped by individual orders.

SELECT SomethingElse, SUM(DataPoint) AS SumOfData
FROM [AAC\vafscjaesct].Whatever
GROUP BY SomethingElse

foo3
bar9
baz22
qux24

 
 

Another example:

SELECT SomethingElse, AVG(DataPoint) AS AvgOfData
FROM [AAC\vafscjaesct].Whatever
GROUP BY SomethingElse

foo1.500000
bar3.000000
baz5.500000
qux8.000000

No comments:

Post a Comment