Solved

query help - aggregate function

Posted on 2007-03-28
4
159 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
Comment Utility
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
Comment Utility
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]
Comment Utility
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
Comment Utility
I use the CTE and it works. Thank you very muich.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how the fundamental information of how to create a table.

763 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

9 Experts available now in Live!

Get 1:1 Help Now