<span class="Apple-style-span" style="border-collapse: collapse; color: rgb(51, 51, 51); font-family: arial, sans-serif; font-size: 13px; ">Anyone up for an SQL query question?  It should be mostly RDBMS-agnostic, but I'm using PostgreSQL 8.4/Ubuntu 11.04.<div>
<br></div><div>I have a table 'tblcategory' and a table 'tbltransdetails'.  The first holds 3 levels of categories, the second holds the details of transactions, and stores the category_id from tblcategory for each transaction_item record.  I have a nice query that shows all my expenses by lowest-level category, but what I want is to show the expenses by the highest-level category.</div>
<div><br></div><div>tblcategory (category_id, category_name, parent_id, lineage, deep)</div><div>tbltransdetails (transdetails_id, transaction_id, category_id, item, size, quantity, amount, note)</div><div><br></div><div>
Category Example:</div><div>Transportation: Auto: Fuel (parent(7): child(55): grandchild(60) with a lineage of 7-55-60 and depth of "2"</div><div><br></div><div>If I do:</div><div>SELECT catgory_name AS "Category", sum(transdetails_amount)</div>
<div>FROM tblcategory c, tbltransdetails d</div><div>WHERE c.category_id = d.category_id</div><div>GROUP BY category_name;</div><div><br></div><div>This gives me the detailed category view, something like: Transportation: Auto: Fuel | 150.00</div>
<div>What I want is to build a query that shows the amounts per *parent* category, not the grandchild category.  In other words, I only want to see Transportation | 250.00</div><div><br></div><div>I can build a query that shows the parent & child categories for all 3 levels, or even for just the first 2 levels by performing a self-join on tblcategory.  I got that down relatively ok.  But I cannot figure out how to select only the top category of the tree and relate it to the summed amounts from the other table.  Can anyone help?<br clear="all">
<br></div><div>Thanks,</div><div>Don</div></span><br>-- <br>D.C. Parris, FMP, LEED AP O+M, ESL Certificate<br>Minister, Security/FM Coordinator, Free Software Advocate<div><a href="https://www.xing.com/profile/Don_Parris" target="_blank">https://www.xing.com/profile/Don_Parris</a>  |  <a href="http://www.linkedin.com/in/dcparris" target="_blank">http://www.linkedin.com/in/dcparris</a></div>
<div>GPG Key ID: F5E179BE</div><br>