簡體   English   中英

MySQL 查詢基於一個共同值從兩個表中求和一列並計算另一列?

[英]MySQL query to sum one column and count another column, from two tables, based on a common value?

我在嘗試構建一個查詢時遇到問題。 我希望在這里能得到一點幫助......

我有兩張桌子。 每個表有兩列。 它們描述如下:

表:“令牌”

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

表:“分數”

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

我想要一個查詢,該查詢將列出每個名稱一次,並為每個名稱列出該名稱的點總和,以及 Color="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

我的表 output 將類似於(行順序不重要):

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

我怎樣才能做到這一點?

您可以聚合,然后加入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM