sql 中有两列,当第一列的字符串相同时,第二列相加
发布网友
发布时间:2023-07-22 11:05
我来回答
共5个回答
热心网友
时间:2023-09-15 11:35
mysql> CREATE TABLE TT ( A VARCHAR(10) NOT NULL,B INT NOT NULL)ENGINE=INNODB DEF
AULT CHARSET=UTF8;
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO TT VALUES ('aa',3),('aa',4),('aa',5);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM TT;
+----+---+
| A | B |
+----+---+
| aa | 3 |
| aa | 4 |
| aa | 5 |
+----+---+
3 rows in set (0.00 sec)
-- 以下两种方法任选
#1:
mysql> SELECT A,SUM(B) FROM TT WHERE A='aa';
+----+--------+
| A | SUM(B) |
+----+--------+
| aa | 12 |
+----+--------+
1 row in set (0.03 sec)
#2:
mysql> SELECT A,SUM(B) FROM TT GROUP BY A;
+----+--------+
| A | SUM(B) |
+----+--------+
| aa | 12 |
+----+--------+
1 row in set (0.00 sec)
热心网友
时间:2023-09-15 11:36
CREATE TABLE #t (A char(2), B int);
INSERT INTO #t
SELECT 'aa', 3 UNION ALL
SELECT 'aa', 4 UNION ALL
SELECT 'aa', 5 UNION ALL
SELECT 'bb', 2 UNION ALL
SELECT 'bb', 3;
SELECT
A,
SUM(B) AS B
FROM
#t
GROUP BY A;
A B
---- -----------
aa 12
bb 5
(2 行受影响)
热心网友
时间:2023-09-15 11:36
select A , B = sum(case when A = 'aa' then B else 0 end ) from table
热心网友
时间:2023-09-15 11:37
select A,sum(B) B
from 表名
group by A
热心网友
时间:2023-09-15 11:37
select a,sum(b) from PM_PRODUCT_T group by a