Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
pixelwiz
Starting Member
25 Posts |
Posted - 2011-02-14 : 13:49:14
|
Hi All,Does anyone know if there is a way to simplify this query? (Hopefully the names are obvious enough, it has to do with golf, courses, and 18 holes, but I need to do total par for front 9 and back 9. I think there is a way to do it using a having clause, but I'm not sure.SELECT c.*, ec.course_priority, ( SELECT SUM(yardage) FROM holes h WHERE h.event_id = ec.event_id AND h.course_id = c.id) yardage,( SELECT SUM(par) FROM holes h WHERE h.event_id = ec.event_id AND h.course_id = c.id AND h.hole_number <= 9) front,( SELECT SUM(par) FROM holes h WHERE h.event_id = ec.event_id AND h.course_id = c.id AND h.hole_number > 9) back, ( SELECT SUM(par) FROM holes h WHERE h.event_id = ec.event_id AND h.course_id = c.id) total FROM courses c INNER JOIN event_courses ec ON ec.course_id = c.id AND ec.event_id = 5001 WHERE c.id IN ( SELECT DISTINCT course_id FROM groups g WHERE g.round = 1 AND g.event_id = ec.event_id ) ORDER BY ec.course_priority |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-02-14 : 14:35:38
|
This is a guess as you didn't provide any DDL, how the tables join or any sample data, but it's a step in the right direction.JimSELECT c.*,ec.course_priority ,[FrontNine] = SUM(CASE WHEN h.holeNumber < 10 THEN par ELSE 0 END) ,[BackNine] = SUM(CASE WHEN h.holeNumber > 9 THEN par ELSE 0 END) ,[Total] = SUM(par) FROM holes hINNER JOIN courses c on h.course_id = c.id and h.INNER JOIN event_courses ec on h.event_id = ec.event_id and c.id = ec.course_idWHERE ec.event_id = 5001GROUP BY <the columns in courses>,ec.course_priority Everyday I learn something that somebody else already knew |
 |
|
|
pixelwiz
Starting Member
25 Posts |
Posted - 2011-02-14 : 15:04:00
|
| Thank you, that was a perfect guess!Now is it actually more efficient to do it that way? |
 |
|
|
dataguru1971
Master Smack Fu Yak Hacker
1464 Posts |
Posted - 2011-02-14 : 15:09:49
|
quote: Originally posted by pixelwiz Thank you, that was a perfect guess!Now is it actually more efficient to do it that way?
Yes, way more efficient that multiple subqueries. Poor planning on your part does not constitute an emergency on my part. |
 |
|
|
Jeff Moden
Aged Yak Warrior
652 Posts |
Posted - 2011-02-14 : 22:43:15
|
quote: Originally posted by pixelwiz Thank you, that was a perfect guess!Now is it actually more efficient to do it that way?
My recommendation would be to open up SQL Profiler and find out! --Jeff Moden |
 |
|
|
|
|
|
|
|