MySQL查询基于一个公共值从两个表中求和一列并计算另一列?

时间:2020-04-29 21:21:03

标签: mysql sql group-by sum where-clause

我在尝试建立的查询时遇到问题。我希望在这里有所帮助...

我有两个桌子。每个表都有两列。它们的描述如下:

表:“令牌”

 Column 1: "Name" varchar(20)
 Column 2: "Color" varchar(10)

表格:“得分”

 Column 1: "Name" varchar(20)
 Column 2: "Points" Int

我想要一个查询,该查询将列出每个名称一次,并且每个名称的总点数以及该位置的颜色=“ RED”

表1的样本数据

"BOB","GREEN"
"LARRY","RED"
"JIM","BLUE"
"JIM","RED"
"FRANK","RED"
"BOB","BLUE"
"JIM","RED"

表2的样本数据

"LARRY",100
"BOB",40
"JIM",200
"BOB",100
"PAUL",250

我的表格输出类似于(行顺序并不重要):

BOB,140,0
LARRY,100,1
JIM,200,2
FRANK,0,1
PAUL,250,0

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以聚合,然​​后加入:

select t1.name, t1.reds, t2.points
from (select name, sum(color = 'RED') reds from table1 group by name) t1
inner join (select name, sum(points) points from table2 group by name) t2 
    on t1.name = t2.name

如果两个表中均缺少name,则可以改用union all

select name, sum(reds) reds, sum(points) points
from 
    select name, 1 reds, 0 points from table1 where color = 'RED'
    union all
    select name, 0, points points from table2
) t 
group by name