Solved

query help - aggregate function

Posted on 2007-03-28
4
164 Views
Last Modified: 2010-03-19
Hi:

I have a table:
EmployeeID   Score
-------------   --------
1                  100
2                     40
3                     40

I want to find out the average score of all employees and the percentage of employees whose score is above average IN ONE QUERY. That is, in this case, the query should return 60 and 0.333. Anyway I can do this? Thanks.
0
Comment
Question by:sdc248
  • 2
  • 2
4 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 250 total points
ID: 18811352
what about this

select  avg_score, ( select cast( count(*) as decimal (10,2)) from yourtable where score >= avg_score) / count_records
from (
select avg(score)  avg_score, count(*) count_records from yourtable
from yourtable
) as l
0
 

Author Comment

by:sdc248
ID: 18811535
Thanks angelIII. I think that'll do it. However, in reality the base table is in fact a result of a complicated sub-query, I don't feel like repeating it in the query. Is there any other way to do it?
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 18811579
with sql server 2005, you can use the CTE (common table expression).
with SQL server 2000 or lower, you could only store the results of the query into a table variable (or temp table), and continue processing from there.
0
 

Author Comment

by:sdc248
ID: 18812008
I use the CTE and it works. Thank you very muich.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now