drqja5919276 2015-01-19 19:30
浏览 43
已采纳

SQL,2表一个字段的总和

I have 2 tables, student and family.

Half of the students come Sundays, the other half Saturdays

Some families have more than one child.

Families pay fees for the school. Some families because of some critearia have a discount.

"discount" is a field in 'family' table

In a report I need to calculate the sum of all the discounts of all families that take advantage of a discount (by day).

When I do so, if a family has 2 children, the result returns double of the discount, if 3 children 3 x discount....

My Query:

$select_total_discounts = 
"SELECT SUM(Discount) AS total_discounts
FROM family, student
WHERE family.Family_ID=student.Family_ID
AND student.Day like '%$Day%'  ;" ; 

$query= mysql_query($select_total_discounts,$conn) ; 
$row = mysql_fetch_assoc($query);
$total_discounts= $row['total_discounts'];

Thank you in advance

  • 写回答

2条回答 默认 最新

  • dousi1961 2015-01-19 20:01
    关注

    If I understood your question correctly, you want to calculate the discounts by family disregarding the amount of students it has. So it'd be like this (change the day value by your variable):

    SELECT SUM(Discount) AS total_discounts
    FROM family 
    WHERE family.Family_ID in (select student.Family_ID from student  where student.Day like 'Monday')
    

    So it sums the discounts of the families that have at least one student from the specified day. If it has one, two, three or more students, it will not affect the result.

    Working SQLFiddle: http://sqlfiddle.com/#!2/9b9793/1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?