Py学习  »  DATABASE

在mysql中将多行合并为一行

Dexter • 4 年前 • 1427 次点击  

distinct 使用sum的行。

+-------+-----+------+------+------+-------+
| users | ref | add  | sub  | mul  | marks |
+-------+-----+------+------+------+-------+
| u1    |  20 | 4521 |      |      |    20 |
| u1    |  20 | 4522 |      |      |    80 |
| u1    |  20 | 4523 |      |      |    60 |
| u1    |  20 |      | 8565 |      |    70 |
| u1    |  20 |      | 8566 |      |    30 |
| u1    |  20 |      |      | 5135 |    10 |
| u2    |  15 | 4521 |      |      |    20 |
| u2    |  15 | 4522 |      |      |    20 |
| u2    |  15 |      | 6253 |      |    30 |
| u3    |  20 | 5236 |      |      |    40 |
| u3    |  20 |      | 4523 |      |    50 |
| u3    |  20 |      | 4524 |      |     5 |
| u3    |  20 |      | 4525 |      |    30 |
| u3    |  20 |      |      | 5135 |    20 |
+-------+-----+------+------+------+-------+

group by 却没有得到这个结果。

+-------+-----+-----+-----+-----+-------+
| users | ref | add | sub | mul | total |
+-------+-----+-----+-----+-----+-------+
| u1    |  20 |   3 |   2 | 1   |   270 |
| u2    |  15 |   2 |   1 | n/a |    70 |
| u3    |  20 |   1 |   3 | 1   |   145 |
+-------+-----+-----+-----+-----+-------+
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54020
 
1427 次点击  
文章 [ 1 ]  |  最新文章 4 年前
forpas
Reply   •   1 楼
forpas    4 年前

这就是你应该用的方法 group by 汇总:

select users, ref,
  count(`add`) `add`,
  count(sub) sub,
  count(mul) mul,
  sum(marks) total
from tablename
group by users, ref

demo
结果:

| users | ref | add | sub | mul | total |
| ----- | --- | --- | --- | --- | ----- |
| u1    | 20  | 3   | 2   | 1   | 270   |
| u2    | 15  | 2   | 1   | 0   | 70    |
| u3    | 20  | 1   | 3   | 1   | 145   |