我在下面有两个查询的SUM值 查询1:*
SELECT SUM(price)FROM TABLE1 WHERE
acc_id
='555'
查询2:
SELECT SUM(price)FROM TABLE2 WHERE
account
='555'&&活性= '1'
我尝试合并这两个查询,但提供了错误的和结果,例如query1 sum is: -86500
和Query2 sum is: 76000
,结果必须为-10500
,但结果显示的数字为{{1} }
我正在尝试这样,但我没有得到预期的结果。
-486000
表格图片:
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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'
答案 3 :(得分: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'
答案 4 :(得分: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')
答案 5 :(得分: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