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条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题