使用SUM(列字段)添加数据值 - MySQL

时间:2017-06-01 09:09:16

标签: mysql sql database join

我正在尝试获取一个列字段的SUM和另一个具有另一个列字段的SUM。问题是,当执行查询时,数字正在累加....

我有不同的类型,想想它,因为类型有自己的值,并且它们是手动编码的,这意味着没有TYPE表但我有一个类型列。每种类型都有不同的数量,当我想得到类型号的总和时......我只需要调用它(例如type =“4”)

我只想得到各自类型的列的总和或总数,但我得到的结果不同,因为他们加起来..有人能给我提供如何做到这一点的想法吗? :(谢谢你。

这是我的疑问:

SELECT a.ID, b.FIRSTNAME, SUM(a.AMOUNT) as TRANSACT, SUM(c.AMOUNT) as 
CALCULATED FROM GNDSALE a 
INNER JOIN emp b ON a.ID= b.ID 
INNER JOIN gndsale c ON c.ID= b.ID 
where a.type = "43" and c.type = "4"
group by a.ID

以下是我得到的结果:

enter image description here

以下是类型为43 的TRANSACTED查询 : enter image description here

这是计算查询,其中类型为4

enter image description here

我想得到的是Traacted和Calculated的结果,而不将查询添加到一起。

1 个答案:

答案 0 :(得分:0)

使用子查询

分离总和(c)
DROP TABLE IF EXISTS A,B,C;

CREATE TABLE A(ID INT, AMOUNT INT, TYPE INT);

CREATE TABLE B(ID INT, FIRSTNAME VARCHAR(10));

CREATE TABLE C(ID INT, AMOUNT INT,TYPE INT);

INSERT INTO A VALUES
(1,10,43),(1,10,50),(2,20,43),(2,20,43);

INSERT INTO B VALUES (1,'AAA'),(2,'BBB');

INSERT INTO C VALUES (1,100,4),(2,200,4);

SELECT a.ID, b.FIRSTNAME, SUM(a.AMOUNT) as TRANSACT, (SELECT SUM(c.AMOUNT) FROM C WHERE C.ID = A.ID AND C.TYPE = 4) as CALCULATED 
FROM  a 
INNER JOIN b ON a.ID= b.ID 
#INNER JOIN c ON c.ID= A.ID 
where a.type = "43" #and c.type = "4"
group by a.ID;

结果

+------+-----------+----------+------------+
| ID   | FIRSTNAME | TRANSACT | CALCULATED |
+------+-----------+----------+------------+
|    1 | AAA       |       10 |        100 |
|    2 | BBB       |       40 |        200 |
+------+-----------+----------+------------+
2 rows in set (0.00 sec)