MySQL组由一列但选择所有其他数据并加总

时间:2016-10-23 07:30:31

标签: mysql

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

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


alex
2700
alex
2700
alex
2700

1 个答案:

答案 0 :(得分:0)

假设您在表中有一个月或某种方式来推导它,您可以使用条件聚合 所以给出了

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)
相关问题