结果不准确使用内连接2查询

时间:2013-12-29 01:08:00

标签: mysql

我想加入以下2个查询:

SELECT DISTINCT kdbaes1, kdsatker, 
                FORMAT (ABS(SUM(rphreal)),0) AS pagu 
FROM budget 
WHERE thnang='2013' AND jnsdok1 IN('202','203') 
GROUP BY kdsatker 
ORDER BY kdbaes1, kdsatker;

SELECT DISTINCT kdbaes1, kdsatker, 
                FORMAT (SUM(rphreal),0) AS realisasi  
FROM real 
WHERE thnang='2013' AND jnsdok1='301' AND kdmakmap LIKE '5%' 
GROUP BY kdsatker 
ORDER BY kdbaes1, kdsatker;

我尝试加入这些查询,但结果在rphreal列中不准确

SELECT DISTINCT budget.kdbaes1, budget.kdsatker, 
                FORMAT (ABS(SUM(budget.rphreal)),0) AS rpbudget, 
                FORMAT (SUM(real.rphreal),0) AS rpreal 
 FROM budget 
 INNER JOIN real ON budget.kdsatker=real.kdsatker
 WHERE budget.thnang='2013' AND budget.jnsdok1 IN('202','203') AND
       real.thnang='2013' AND real.jnsdok1='301' AND real.kdmakmap LIKE '5%' 
 GROUP BY kdsatker  
 ORDER BY kdbaes1, kdsatker;

需要帮助..

1 个答案:

答案 0 :(得分:0)

我根据我认为你想要实现的目标进行猜测......

  SELECT DISTINCT budget.kdbaes1, budget.kdsatker, 
                    FORMAT (ABS(SUM(budget.rphreal)),0) AS rpbudget, 
                    FORMAT (SUM(real.realisasi),0) AS rpreal 
     FROM budget 
     INNER JOIN 
     (SELECT DISTINCT kdbaes1, kdsatker, 
                FORMAT (SUM(rphreal),0) AS realisasi  
      FROM real 
      WHERE thnang='2013' AND jnsdok1='301' AND kdmakmap LIKE '5%' 
      GROUP BY kdsatker
     ) real on real.kdbaes1 = budget.kdbaes1 AND real.kdsatker = budget.kdsatker 

     WHERE budget.thnang='2013' AND budget.jnsdok1 IN('202','203') 
     GROUP BY kdsatker  
     ORDER BY kdbaes1, kdsatker;

您似乎正在尝试对JOIN示例中的两个单独的表执行SUM。

我所做的是采取你的第二个查询并使其成为子查询来执行真实表的SUM。然后,我们使用此子查询加入预算表...