This may not be possible in one query, but I'd like to see what my options are.
I have a large query that returns the data for each piece of an inventory (in this case trees). The query gets data from a few different tables. I mostly use left outer joins to bring this information in, so if it's not there I can ignore it and take the NULL. I have an interesting situation where a one-to-many relationship exists between "tree" and it's "pests".
- tree table: treeID, treeHeight, etc....
- pest (pest to tree) table: pestID, treeID, pestRef.....
I need a query that gets the top 6 pests for each tree and returns them as columns:
- pest1, pest2, pest3... and so on.
I know that I could do this in multiple queries, however that would happen thousands of times just per use and our servers can't handle that.
Some notes: we're using ColdFusionMX7, and my knowledge of stored procedures is very low.
One approach is to generate a column representing the pest rank by tree, then join the ranked pest table to the tree table with rank as a join condition. Make sure you use ROW_NUMBER not RANK because a tie would cause repeated numbers in RANK (but not ROW_NUMBER), and make sure you use LEFT OUTER joins so trees with fewer pests are not excluded. Also, I ordered by 2 conditions, but anything valid in a normal ORDER BY clause is valid here.