SQL Join 2表有2个计数

时间:2014-03-10 11:57:19

标签: sql oracle tsql

我会尝试解释我的问题:

我有类似的查询:

第一个

SELECT MOD_DESC, MOD_COD, COUNT(MOD_DESC) AS NUM
FROM MODELLI, PV_PROPOSTI, GESTIONE_COMMESSE 
WHERE  Something

第二个

SELECT MOD_DESC, MOD_COD, COUNT(MOD_DESC) AS NUM 
FROM DISTRIB, MODELLI 
WHERE Something

现在,其结果是'非常相似,因为唯一的区别是where条件:

 MOD_DESC   MOD_COD  NUM 
 desc1      cod1     2  
 desc2      cod2     1  
 desc3      cod3     3  

 MOD_DESC  MOD_COD  NUM 
 desc1      cod1     5  
 desc2      cod2     2  
 desc4      cod4     3  

但现在我想"合并" 2个查询并得到像

这样的结果
 MOD_DESC  MOD_COD  NUM1  NUM2 
 desc1      cod1     2      5  
 desc2      cod2     1      2  
 desc3      cod3     3      0  
 desc3      cod3     0      3  

我已尝试过此查询:

SELECT t2.MOD_DESC, t2.MOD_COD, COUNT(t2.MOD_DESC) as NUM1, COUNT(t1.MOD_DESC) as NUM2
FROM ( 

       SELECT MOD_DESC, MOD_COD
       FROM MODELLI, PV_PROPOSTI, GESTIONE_COMMESSE 
       WHERE  something
      ) t1  

      RIGHT JOIN 
      ( 
       SELECT MOD_DESC, MOD_COD 
       FROM DISTRIB, MODELLI 
       WHERE Something

      ) t2 ON t1.MOD_COD = t2.MOD_COD 

GROUP BY t2.MOD_DESC, t2.MOD_COD
ORDER BY t2.MOD_DESC, t2.MOD_COD

但我没有得到相关结果。

一些帮助?

(我在oracle db上)

3 个答案:

答案 0 :(得分:1)

一些注释。

1)在子查询中进行计数,而不是在外部查询中进行计数。在计数之前加入您的结果将改变计数的结果。

2)如果一个子查询中存在记录而另一个子查询中没有记录,则使用FULL OUTER JOIN

3)加入BOTH字段(MOD_DESC和MOD_COD),而不只是一个

SELECT
  *
FROM
(
  SELECT MOD_DESC, MOD_COD, COUNT(MOD_DESC) AS NUM
  FROM MODELLI, PV_PROPOSTI, GESTIONE_COMMESSE 
  WHERE  Something
)
  AS MPG
FULL OUTER JOIN
(
  SELECT MOD_DESC, MOD_COD, COUNT(MOD_DESC) AS NUM 
  FROM DISTRIB, MODELLI 
  WHERE Something
)
  AS DM
    ON  DM.MOD_DESC = MPG.MOD_DESC
    AND DM.MOD_COD  = MPG.MOD_COD

答案 1 :(得分:1)

你没有解释你有什么不正确的结果。

但我建议你尝试这样的事情:

SELECT COALESCE(t1.MOD_DESC, t2.MOD_DESC) AS MOD_DESC,
       COALESCE(t1.MOD_COD, t2.MOD_COD) AS MOD_COD,
       COUNT(t2.MOD_DESC) as NUM1,
       COUNT(t1.MOD_DESC) as NUM2
  FROM ( query 1 ) AS t1 FULL OUTER JOIN
       ( query 2 ) AS t2 ON t1.MOD_COD = t2.MOD_COD
 GROUP BY COALESCE(t1.MOD_DESC, t2.MOD_DESC) AS MOD_DESC,
          COALESCE(t1.MOD_COD, t2.MOD_COD) AS MOD_COD
 ORDER BY MOD_DESC, MOD_COD

答案 2 :(得分:-3)

您需要使用FULL OUTER JOIN