SQL加入两个查询并总结记录

时间:2018-04-09 19:38:07

标签: sql asp.net vb.net db2

我正在使用asp.net编写一个Web表单页面。我有两张不同的桌子。两个表都有相同的列,只有不同的数据。例如:

Table 1: col1,  col2,  col3
         123   $12.54   Tom
          34   $7.00    Jan

Table 2: col1,  col2,  col3
         123   $125.00  Tom
         56    $12.00   Joe

我正在尝试编写一个将两个表组合在一起的sql语句,如果表1中的Col1与表2中的col1相同,我想将第2列的值一起添加。例如:

Col1     col2     col3
123      $137.54    Tom
34       $7.00      Jan
56       $12.00     Joe

以下是sql查询:

表1:

SELECT ABAN8 as Number, SUM(SDAEXP * .01) as SaleAmount, A5POPN as Rep 
FROM KAIPRDDTA.F0101, KAIPRDDTA.F4211, KAIPRDDTA.F0301 
WHERE A5AN8 = ABAN8 
 AND ABAN8 = SDAN8 
 AND SDKCOO = '00001' 
 AND SDDCTO not like '%2' 
 AND A5DAOJ >= '118069' 
 AND A5DAOJ <= '118099' 
 GROUP BY ABALPH, A5POPN, ABAN8, A5UPMT, A5CMC1

表2:

SELECT ABAN8 as Number, SUM(SDAEXP * .01) as SaleAmount, A5POPN as Rep 
FROM KAIPRDDTA.F0101, KAIPRDDTA.F42119, KAIPRDDTA.F0301 
WHERE A5AN8 = ABAN8 
 AND ABAN8 = SDAN8 
 AND SDKCOO = '00001' 
 AND SDDCTO not like '%2' 
 AND A5DAOJ >= '118069' 
 AND A5DAOJ <= '118099' 
 GROUP BY ABALPH, A5POPN, ABAN8, A5UPMT, A5CMC1

我知道加入语法已过时,但这就是该公司如何使用它。如果您需要更多信息,请提前告知我们,并提前感谢您的回复!

2 个答案:

答案 0 :(得分:2)

嗯,合并和完全外连接基本上相当容易,但我不知道db2是否支持隐式全外连接。

我要解决您发布的示例数据,而不是查询,因为我希望能够阅读我写的内容,因为我觉得它会有很多对于那些想要阅读本文的人来说更清楚 - 所以这里有:

SELECT COALESCE(t1.col1, t2.col1) As col1, 
       COALESCE(t1.col2, 0) +  COALESCE(t2.col2, 0) As col2, 
       COALESCE(t1.col3, t2.col3) As col3
FROM table1 as t1
FULL JOIN table12 as t2 ON t1.col1 = t2.col1

据我了解,DB2 supports implicit left joins and implicit right joins。我无法找到关于完全加入的任何内容,但我认为它应该像这样工作:

FROM table1 as t1, table2 as t2
WHERE t1.col1(+) = t2.col1(+)

答案 1 :(得分:0)

&#34;分组中的5列&#34;只选择了2列。对于给定的数字和代表,您可能会获得多条记录。检查&#34; UNION ALL&#34;符合您的要求。

Select number, sum(SaleAmount) , Rep
from
( SELECT ABAN8 as Number, (SDAEXP * .01) as SaleAmount, A5POPN as Rep 
FROM KAIPRDDTA.F0101, KAIPRDDTA.F4211, KAIPRDDTA.F0301 
WHERE A5AN8 = ABAN8 
 AND ABAN8 = SDAN8 
 AND SDKCOO = '00001' 
 AND SDDCTO not like '%2' 
 AND A5DAOJ >= '118069' 
 AND A5DAOJ <= '118099' 
union all
SELECT ABAN8 as Number,  (SDAEXP * .01) as SaleAmount, A5POPN as Rep 
FROM KAIPRDDTA.F0101, KAIPRDDTA.F42119, KAIPRDDTA.F0301 
WHERE A5AN8 = ABAN8 
 AND ABAN8 = SDAN8 
 AND SDKCOO = '00001' 
 AND SDDCTO not like '%2' 
 AND A5DAOJ >= '118069' 
 AND A5DAOJ <= '118099' 
) a 
group by number , rep