我有一张桌子,看起来像这样:

studentid | studentname | fee | latfeecharges | dues
1         | Alex        | 2000 | 200           | 500
1         | Alex        | 2000 | 200           | 500
1         | Alex        | 2000 | 200           | 500


我想要以下结果:

Alex

2700
2700
2700


因此,在这种情况下,将feelatefeechargesdues相加,我将它们分别获取,但只想一次获得名称。我怎么做?

现在我通过使用此查询获得此结果


$ query =“ SELECT * FROM table ORDER BY studentid”;




亚历克斯
2700
亚历克斯
2700
亚历克斯
2700

最佳答案

假设您的表中有一个月或以某种方式导出该月,则可以使用条件聚合
所以给

MariaDB [sandbox]> select * from t;
+-----------+-------------+------+----------------+------+------+
| studentid | studentname | fee  | latefeecharges | dues | MTH  |
+-----------+-------------+------+----------------+------+------+
|         1 | Alex        | 2000 |            200 |  500 |    1 |
|         1 | Alex        | 2000 |            200 |  500 |    2 |
|         1 | Alex        | 2000 |            200 |  500 |    3 |
+-----------+-------------+------+----------------+------+------+
3 rows in set (0.00 sec)

MariaDB [sandbox]> select studentname,
    -> sum(case when mth = 1 then fee+latefeecharges+dues else 0 end) month1,
    -> sum(case when mth = 2 then fee+latefeecharges+dues else 0 end) month2,
    -> sum(case when mth = 3 then fee+latefeecharges+dues else 0 end) month3
    -> from t
    -> group by studentname;
+-------------+--------+--------+--------+
| studentname | month1 | month2 | month3 |
+-------------+--------+--------+--------+
| Alex        |   2700 |   2700 |   2700 |
+-------------+--------+--------+--------+
1 row in set (0.00 sec)

关于mysql - MySQL按一列分组,但选择所有其他数据并将其求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40200605/

10-13 00:58