Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

avg query with a lookup 1

Status
Not open for further replies.

evan1t

Vendor
Mar 14, 2007
2
GB
I am trying to develop a query in WinSQL, and I am having a very hard time with it. I am hoping that someone here can help me.

I have two tables: 1) a doctors table, with a doc_id (numeric identifying code), and a first and last name for each doctor, and 2) a list of patients' stays in the hospital broken down by length of stay (stay_length) and doctor ID.

I can generate a report listing the average stay by doctor ID:
select s.doctor, avg(s.stay_length) "Average Stay"
from system.patient_stays s
group by s.doctor
order by avg(s.stay_length) desc;



What I want to do is annotate that listing with each doctor's name instead of just the ID number. Attempts have given me errors:

select s.doctor, d.firstname, d.lastname, avg(s.stay_length) "Average Stay"
from system.patient_stays s, doctors d
where doc_id=doctor
group by s.doctor
order by avg(s.stay_length) desc;


generates: Non-grouped column in SELECT or HAVING


If I leave out the group by clause, I get:
Some column are under set functions and some are not.



Help please...?

thank you!
Evan
 
Hi Evan,

Try this out:

Code:
select s.doctor, d.firstname, d.lastname, avg(s.stay_length) "Average Stay"
from system.patient_stays s, doctors d
where doc_id=doctor
group by s.doctor, d.firstname, d.lastname
order by avg(s.stay_length) desc;

Everything in your select taht an aggregate is not applied to must be included in your group by.

Hope this helps,

Alex

Ignorance of certain subjects is a great part of wisdom
 
That did it!

Thank you very much, Alex!
Evan
 
Glad it helped :)

Ignorance of certain subjects is a great part of wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top