[英]Mysql query that includes TWO sums from columns in other tables
Got a query running one sum from a different table, which works perfectly (and obtained from this forum as well): 得到了一个查询,该查询在另一个表中运行一个总和,该查询非常有效(也可以从该论坛获得):
SELECT
R.REP_ID as repid, R.REP_DESBREV as repdesc,
IFNULL(SUM(RD.REPDATA_CANT), 0) as cant
FROM
REPUESTOS R
LEFT JOIN
REP_DATA RD, ON RD.REPDATA_REPID = R.REP_ID
GROUP BY
RD.REPDATA_REPID
Now, the thing is that I'd like to add an extra column that obtains the total inventory (something like 现在,我想添加一个额外的列来获取总库存(例如
IFNULL(SUM(I.INV_CANT), 0) as inv)
FROM table INVENTARIO I
WHERE I.INV_REPID = R.REP_ID
This value can be obtained by means of a JOIN, in the exact same way we got the first statement that works, but I have not found the way to include BOTH SUMS in just one query. 可以通过JOIN来获得该值,这与我们获得第一个有效语句的方式完全相同,但是我还没有找到仅在一个查询中包含BOTH SUMS的方法。
Any ideas? 有任何想法吗? THANKS! 谢谢!
Try this query example 试试这个查询例子
select
t1.id,
ifnull(sum(t1.my_column),0) as Sum1,
ifnull(other.sum,0) as Sum2
from table as t1
left join (select id , sum(other_table_column) from other_table group by id) as other
on t1.id = other.id
group by t1.id
I just implemented the following statement: 我刚刚实现了以下语句:
SELECT
R.REP_PARNUM as parnum,
R.REP_ID as repid,
R.REP_DESBREV as repdesc,
IFNULL(SUM(RD.REPDATA_CANT),0) as cant,
IFNULL(SUM(I.INV_CANT),0) as intt
FROM REPUESTOS R
LEFT JOIN REP_DATA RD ON RD.REPDATA_REPID = R.REP_ID
LEFT JOIN INVENTARIO I ON I.INV_REPID = R.REP_ID
GROUP BY R.REP_PARNUM
It actually runs, but the problem is that it's giving me some weird values. 它实际上在运行,但是问题是它给了我一些奇怪的值。 For example, some of the values in the first sum column ( REPDATA_CANT
) are shown with -3, ie if the real result is 20, it shows 17 and so on. 例如,第一和列( REPDATA_CANT
)中的某些值显示为-3,即,如果实际结果为20,则显示17,依此类推。 In the second sum column ( INV_CANT
), it actually MULTIPLIES (in some rows, not all) the value by 3. Very weird behaviour, do you have an idea why? 在第二个总和列( INV_CANT
)中,它实际上乘以3(在某些行中,不是全部)该值。非常奇怪的行为,您知道为什么吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.