Stuck on Query

  • So I'm a bit stuck on this problem and wanted to see if any of the gurus out there had any thoughts of where I might be going wrong

    End Result: I need to create an SQL query from a master/detail relationship to show me records where the SUM of the detail record's "Amount Paid" field equal or are more than 75% of the equipments master record field "Equipment Total Cost". This is in effort to display a list of pieces of equipment where it makes sense to purchase rather than continue to rent and avoid over paying the total value cost.

    In my example, I have a master / detail table relationship (linked on ID#)

    Master table: ID#, Equipment Name, Equipment Total Cost

    Detail Table: ID#, Invoice Number, Amount Paid

    I think I'm on the right path by doing a "SUM (Amount Paid) As "Invoice Total Paid" (I know SUM will just add, i still need to /divide by Total cost *100 for percent, but trying to just get the addition idea down) ....and then adding the other fields into a "GROUP BY" clause at the bottom, but for some reason, the addition of the "Amount Paid" field from the detail table isn't happening...the SUM doesn't seem to be doing anything. The query runs just fine, and it makes a new field in my result set, but the SUM never happens, it just returns what the original "Amount Paid" field was. As I mentioned, i had to put the remaining fields into a "GROUP BY" at the end because SQL tells me they either need to be in a group by or an aggregate, and this might be where my problem is....

    Any help would be so very much appreciated!

    Thanks!

  • Since you didn't provide the code you are currently using I'll just give you what I would do:

    SELECT

    MT.equipment_name,

    MT.total_cost,

    SUM(DT.amount_paid) AS total_paid,

    (SUM(DT.amount_paid)/MT.total_cost) * 100 AS percent_of_total_cost_paid

    FROM

    master_table MT JOIN

    detail_table DT ON

    MT.id = DT.id

    GROUP BY

    MT.equipment_name,

    MT.total_cost

    /*

    Having is like a WHERE AFTER the grouping is done

    */

    HAVING

    ((SUM(DT.amount_paid)/MT.total_cost) * 100) >= 75

  • Woot! everything works as expected now! Thank you so much!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply