首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mysql计数列值和合并列

Mysql计数列值和合并列
EN

Stack Overflow用户
提问于 2015-08-04 11:03:42
回答 3查看 149关注 0票数 0

我在根据给定的字段值分组来创建计数行时遇到了问题。例如:我有一个表--结构,如下所示:

代码语言:javascript
复制
+------+------------+
| id   |  Person    |
+------+------------+
| 1    | "Sandy"    |
| 2    | "Piper"    |
| 3    | "Candy"    |
| 4    | "Pendy"    |
+------------+------+

我还有一个表B结构,如下所示:

代码语言:javascript
复制
+------+------------+---------+
| id   |  Person    |  Point  |
+------+------------+---------+
| 1    | "Sandy"    |  10     |
| 2    | "Piper"    |  20     |
| 3    | "Candy"    |  30     |
| 4    | "Sandy"    |  10     |
| 5    | "Piper"    |  20     |
| 6    | "Zafar"    |  30     |
+------------+------+---------+

需要这样的结果:

代码语言:javascript
复制
+------+------------+---------+
| id   |  Person    |  Point  |
+------+------------+---------+
| 1    | "Piper"    |  40     |
| 2    | "Candy"    |  30     |
| 3    | "Zafar"    |  30     |
| 4    | "Sandy"    |  20     |
| 5    | "Pendy"    |   0     |
+------------+------+---------+

我希望表中的例子本身是不言自明的。

EN

回答 3

Stack Overflow用户

发布于 2015-08-04 11:33:00

代码语言:javascript
复制
SELECT person
     , SUM(point) total 
  FROM 
     ( SELECT person,point FROM table_b
        UNION 
          ALL
       SELECT person,0 FROM table_a
     ) x
 GROUP 
    BY person 
 ORDER 
    BY total DESC;
票数 3
EN

Stack Overflow用户

发布于 2015-08-04 11:09:26

它是一个简单的left join,有一个group by

代码语言:javascript
复制
select tableA.person, sum(tableB.points) from tableA left join tableB on tableA.person = tableB.person group by tableA.person
union
select tableB.person, sum(tableB.points) from tableB left join tableA on tableA.person = tableB.person  where tableA.id is null group by tableA.person
票数 2
EN

Stack Overflow用户

发布于 2015-08-04 11:08:23

我认为下面的sql对您有用。

代码语言:javascript
复制
select a.id, a.Person,b.total_point  from (
select id, Person from tablea) as a join

(select Person, sum(Point) as total_point from tableb group by person) as b on a.person =b.person

谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31807578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档