3

我有以下两个查询的 SUM 值
Query1:*

从表 1 中选择总和(价格),acc_id其中 = '555'

查询2:

从表 2 中选择总和(价格)account,其中 = '555' && active='1'

我尝试将这两个查询结合起来,但给出错误的求和结果,例如如果query1 sum is: -86500Query2 sum is: 76000,RESULT 必须是-10500,但结果显示为数字-486000

我正在尝试这样,但我没有得到预期的结果。

SELECT SUM(t1.price + t2.price) AS TotalCredit 
FROM TABLE1 AS t1, TABLE2 AS t2 
WHERE t1.`acc_id` = '555' && t2.`Account`='555' && t2.`Active`='1'

表图像:在此处输入图像描述

4

6 回答 6

5

由于加入记录的数量会重复,并且您会获得更高的总和值,请尝试此

SELECT sum(prc) 
FROM (
    SELECT SUM(price) prc FROM TABLE1 WHERE acc_id = '555'
    union all 
    SELECT SUM(price) prc FROM TABLE2 WHERE account = '555' && active='1'
) a
于 2012-12-24T16:57:06.083 回答
1

尝试这个

SELECT SUM(C.TOTAL) AS TOTAL_CREDIT FROM (SELECT SUM(A.price) AS TOTAL FROM TABLE1 A WHERE A.acc_id = '555'
UNION ALL
SELECT SUM(B.price) AS TOTAL FROM TABLE2 B WHERE B.account = '555' && B.active='1') C;
于 2012-12-24T16:56:13.840 回答
0

试试看

SELECT (SUM(t1.price) + SUM(t2.price)) AS TotalCredit 
FROM TABLE1 AS t1, TABLE2 AS t2 
WHERE t1.`acc_id` = '555' && t2.`Account`='555' && t2.`Active`='1'
于 2012-12-24T16:56:52.310 回答
0

这个怎么样:

SELECT SUM(a) 
FROM
  (SELECT SUM(price) AS a
   FROM TABLE1 
   WHERE acc_id = '555'
   UNION ALL
   SELECT SUM(price) AS a
   FROM TABLE2 
   WHERE account = '555' && active='1')
于 2012-12-24T17:06:34.460 回答
0

Join有待改善。:) 如果您可以向我们展示表模式,那就更好了。这是基于一些假设样本数据的解决方案。

样本数据:

表格1:

ID  PRICE
11  200
55  300
33  200
44  100
55  500

表2:

ID  PRICE   ACTIVE
1   200     0
2   300     1
55  200     0
55  100     1
55  400     1

询问:

select sum(t.price) + x.tb2credit
from tb1 as t
inner join
(SELECT id, SUM(price) AS Tb2Credit 
FROM tb2
WHERE id = 55
and `Active`=1) x
on t.id = x.id

结果:

SUM(T.PRICE) + X.TB2CREDIT
1300
于 2012-12-24T17:09:55.070 回答
0

尝试这个

  SELECT (t1.price + t2.price) AS TotalCredit 
    FROM TABLE1 AS t1, TABLE2 AS t2 
    WHERE t1.`acc_id` = '555' && t2.`Account`='555' && t2.`Active`='1'

编辑:

我想你在找什么

 SELECT (SUM(t1.price)+SUM(t2.price) )/2  AS TotalCredit 
FROM Table1 AS t1, Table2 AS t2 
WHERE t1.`acc_id` = '555' && t2.`account`='555' && t2.`active`='1'

演示小提琴在这里

于 2012-12-24T16:49:31.110 回答