[英]SQL sum column in one table where value in another table is 'S'
I have 2 tables: 我有2张桌子:
[rolls]
tappi zone poids
N1001 101 502
N1002 102 502
N1003 103 1008
N1004 104 1008
[zones]
nom type
101 P
102 P
103 S
104 S
What I want to do is sum 'rolls'.'poids' if 'rolls'.'zone' has the type 'S' (according to table 'zones') 我想做的是如果'rolls..zone'具有类型'S'(根据表'zones')的总和'rolls'。'poids'
Output should be 2016 (1008+1008) 输出应为2016(1008 + 1008)
SELECT SUM(t1.poids)
FROM rolls t1
INNER JOIN zones t2
ON t1.zone = t2.nom
WHERE t2.type = 'S'
We can safely do an INNER JOIN
here because if a record from rolls
does not match to anything in zones
then we know that it cannot be zone type S
. 我们可以在这里安全地进行
INNER JOIN
,因为如果rolls
记录与zones
任何内容都不匹配,那么我们知道该记录不能是区域类型S
SELECT SUM(rolls.poids) FROM rolls JOIN zones ON rolls.zone = zones.nom WHERE zones.types ='S'; 从卷中选择SUM(rolls.poids)JOIN在rolls.zone = zone.nom WHERE zone.types ='S'上的区域;
By using JOIN we are looking for the the data that the rolls table and zones table have and by using ON we are limiting to find the data where they have an column in common. 通过使用JOIN,我们正在寻找rolls表和zones表具有的数据,而通过使用ON,我们将限制在具有共同列的位置查找数据。 The goal here is to combine these tables.
这里的目标是合并这些表。 So that would happen:
这样就会发生:
[[rolls] JOINED [zones]]
tappi zone poids nom type
N1001 101 502 101 P
N1002 102 502 102 P
N1003 103 1008 103 S
N1004 104 1008 104 S
Using the where we would segment even more our query to find only records with type S . 使用where可以细分更多的查询,以仅查找类型为S的记录。 So now you are looking at:
所以现在您正在看:
[[rolls] JOINED [zones]]
tappi zone poids nom type
N1003 103 1008 103 S
N1004 104 1008 104 S
And even further you would be looking for this record and saying to yourself. 甚至更进一步,您将寻找该记录并对自己说。 I just want the sum of the poids.
我只想要总和。 So then you use a SELECT SUM(rolls.poids) and the final result is:
因此,您使用一个SELECT SUM(rolls.poids) ,最终结果是:
[sum(rolls.poids)]
2016
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.