示例表
+----+---------+--------+-------+
| PK | Comp | Amount | Class |
+----+---------+--------+-------+
| A1 | Alpha | 2.00 | BA |
| A1 | Alpha | 2.00 | BA |
| B1 | Bravo | 1.50 | BA |
| B1 | Bravo | 1.50 | BA |
| C1 | Charlie | 2.00 | BC |
| C1 | Charlie | 2.00 | BC |
| D1 | Delta | 2.20 | BC |
| D1 | Delta | 2.20 | BC |
| D2 | Delta | 1.70 | BC |
| D2 | Delta | 1.70 | BC |
| E1 | Echo | 3.10 | BD |
| E1 | Echo | 3.10 | BD |
| E2 | Echo | 3.00 | BD |
| E2 | Echo | 3.00 | BD |
| E3 | Echo | 2.90 | BD |
| E3 | Echo | 2.90 | BD |
| E4 | Echo | 2.50 | BD |
| E4 | Echo | 2.50 | BD |
| E5 | Echo | 3.10 | BD |
| E5 | Echo | 3.10 | BD |
+----+---------+--------+-------+
我怎样ADD
每个PK
的第一个值?我一直在使用
SUM(Amount) AS TotalAmount...GROUP BY Class
这就是结果。
+----+---------+--------+-------+-------------+
| PK | Comp | Amount | Class | TotalAmount |
+----+---------+--------+-------+-------------+
| A1 | Alpha | 2.00 | BA | 7.00 |
| C1 | Charlie | 2.00 | BC | 11.80 |
| E1 | Echo | 3.10 | BD | 29.20 |
+----+---------+--------+-------+-------------+
它添加了所有Amount
我使用了SUM(MAX(Amount)) AS TopAmount
,但收到了错误
我想有这张桌子
+----+---------+--------+-------+-------------+
| PK | Comp | Amount | Class | TotalAmount |
+----+---------+--------+-------+-------------+
| A1 | Alpha | 2.00 | BA | 3.50 |
| C1 | Charlie | 2.00 | BC | 5.90 |
| E1 | Echo | 3.10 | BD | 14.6 |
+----+---------+--------+-------+-------------+
像这样但只是每个PK
+-------------------+-------+-------------+
| Amount | Class | TotalAmount |
+-------------------+-------+-------------+
| (A1+B1) | BA | 3.50 |
| (C1+D1+D2) | BC | 5.90 |
| (E1+E2+E3+E4+E5) | BD | 14.6 |
+-------------------+-------+-------------+
感谢您的时间..
答案 0 :(得分:1)
试试这个:
select Class ,SUM(Amount) AS TotalAmount from
(select distinct pk,comp,amount,class from have)
group by class;
答案 1 :(得分:1)
试试这个。将t1
替换为您的表名
SELECT GROUP_CONCAT(PK SEPARATOR '+'), Class ,SUM(Amount) AS
TotalAmount FROM
(SELECT DISTINCT PK, Comp, Amount, Class FROM t1) AS t2
GROUP BY Class;