|
|
Subject:
MS SQL 2000: AVG of TOP n values in a rolling series
Category: Computers > Programming Asked by: caderoux-ga List Price: $2.00 |
Posted:
21 Mar 2003 14:36 PST
Expires: 20 Apr 2003 15:36 PDT Question ID: 179330 |
I have a statistical data warehouse with statistical records for offices per month: Office (varchar(50) Month (smalldatetime) Collections (float) I'd like to extract a time series of the average of the top 20 offices' collections in a resultset which is one record per month. e.g. the top 20 offices in a given month are taken, averaged and related to that month: Month, AvgTopCollections Ideally somthing like: SELECT Month, AVG(TOP 20 Collections) FROM Stats GROUP BY Month I know how to do it for all offices and one office, but I cannot get any one the many types of correlated subqueries I've tried to properly parse. The final goal is to compare a single office to company-wide average and best-practices average over time in a simple line graph with three lines. Is there no way but to open a cursor? |
|
Subject:
Re: MS SQL 2000: AVG of TOP n values in a rolling series
Answered By: mmastrac-ga on 22 Mar 2003 11:58 PST |
This SQL is generated not knowing exactly what your DB structure is like. I'm assuming that your Stats table has an Office_ID as a primary key and "Sales" as the number you are interested in. SELECT Month, AVG(Sales) FROM Stats as s1 WHERE Office_ID IN (SELECT TOP 20 Office_ID FROM Stats as s2 where s2.Month = s1.Month ORDER BY SALES) GROUP BY Month The inner query in this statement selects the TOP 20 offices for a particular month. This query is joined to the outer query's Stats table's month. The outer table is grouped by |
|
Subject:
Re: MS SQL 2000: AVG of TOP n values in a rolling series
From: george_jempty-ga on 21 Mar 2003 18:34 PST |
What on earth is wrong with opening a cursor?!? |
Subject:
Re: MS SQL 2000: AVG of TOP n values in a rolling series
From: caderoux-ga on 22 Mar 2003 06:11 PST |
There is nothing wrong with opening a cursor, and I think many times it can be a very efficient way to solve a problem. I was thinking there might be a way in SQL which is easy. For instance, SELECT COUNT(DISTINCT x) FROM y is valid SQL and useful, yet is not immediately discernable from most documentation and saves having to do SELECT COUNT(*) FROM (SELECT DISTINCT x FROM y). I was wondering if there was a way to easily get an aggregare average of a subset within a group. |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
Search Google Answers for |
Google Home - Answers FAQ - Terms of Service - Privacy Policy |