gpt4 book ai didi

MySQL 按一列分组,但选择所有其他数据并将其求和

转载 作者:行者123 更新时间:2023-11-29 20:09:58 26 4
gpt4 key购买 nike

我有一个表,如下所示:

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 ";
alex2700alex2700alex2700

最佳答案

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

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 按一列分组,但选择所有其他数据并将其求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com