这是我的表
+------+------+-------------+
| sid | cid | amount |
+------+------+-------------+
| 32 | 1 | 500 |
+------+------+-------------+
| 33 | 1 | 300 |
+------+------+-------------+
| 32 | 2 | 500 |
+------+------+-------------+
| 33 | 2 | 400 |
+------+------+-------------+
| .. | . | ... |
+------+------+-------------+
| .. | . | ... |
+------+------+-------------+
| 32 | n | 100 |
+------+------+-------------+
| 33 | n | 100 |
+------+------+-------------+
在我看来,我想在我的视图中显示它,如
+------+----------+-----------+------+------------+------------+
| sid | amount(1)| amount(2) | ... | amount(n) |Total amount|
+------+----------+-----------+------+------------+------------+
| 32 | 500 | 500 | ... | 100 |1100 |
+------+----------+-----------+------+------------+------------+
| 33 | 300 | 400 | ... | 100 |800 |
+------+----------+-----------+------+------------+------------+
我该怎么做?
答案 0 :(得分:2)
您可以使用SQL的GROUP_CONCAT
,SUM
和GROUP
子句。但是,金额不会有多列。 sid的金额列表将全部在一个列中,其值以逗号分隔。
SELECT sid,
GROUP_CONCAT(amount) AS amount,
SUM(amount) AS total
FROM mytbl
GROUP BY sid;