简体   繁体   English

SQL,2个表的一个字段的总和

[英]SQL, 2 tables sum of a field

I have 2 tables, student and family . 我有2张桌子, studentfamily

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.... 当我这样做时,如果一个家庭有2个孩子,那么如果3个孩子3 x折扣,则结果返回折扣的两倍。

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 先感谢您

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 正常的SQLFiddle: http ://sqlfiddle.com/#!2 / 9b9793 / 1

It is not really full answer, but I posted it here, so it would be readable. 这并不是一个完整的答案,但我将其发布在此处,因此可读性强。

I think you are looking for something like UNION : 我认为您正在寻找UNION东西:

SELECT sum(value) FROM ((SELECT value FROM table) UNION ALL (SELECT value FROM table2)) sq

UNION merges your tables vertically. UNION垂直合并您的表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM