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!

multiple aggregation and nested queries

Status
Not open for further replies.

dkalina

Programmer
Oct 4, 2006
1
US
I am trying to get a weighted average rating for photos based on the user group that rated them. I would like to do this forumla in SQL (not pull it back out into a programming language because I would like to pull the results in groups of 10 to display in an app.

The query I currently have returns all the data in row form but doesn't allow me to work with the aggregates, I need to do aggregates like averaging g1 and g2 as well as a couple if statements . I am getting the feeling that I am going to have to redo my nested queries to put this stuff in the FROM area. I tried some but it does not work. Here is the query I am using:

select Distinct users.id, users.first_name, users.last_name, users.dir_name, photos.id, photos.photo_name, photos.

photo_desc, photos.date_created, photos.hilite, count(photos.id) as counter,
(
select IFNULL(SUM(a.my_vote)/count(a.id),0) from votes as a where a.user_type = 3 and a.artist = users.id
) as g1,
(
select IFNULL(SUM(a.my_vote)/count(a.id),0) from votes as a where a.user_type = 2 and a.artist = users.id
) as g2,
(
select IFNULL(SUM(a.my_vote)/count(a.id),0) from votes as a where a.user_type = 5 and a.artist = users.id
) as g3,
(
select IFNULL(SUM(a.my_vote)/count(a.id),0) from votes as a where a.user_type = 4 and a.artist = users.id
) as g4

From users, photos
left join photos ctr On photos.artist=users.id
WHERE users.id=photos.artist AND ctr.artist=users.id AND users.is_artist = 1
GROUP BY users.id, ctr.artist HAVING counter > 5
ORDER BY photos.hilite
;

Any help is most appreciated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top