SUM条件的SELECT子句

时间:2014-05-18 01:27:23

标签: sql oracle

有这张桌子:

//TEST
NUMBER             TOTAL
----------------------------
  1                158
  2                355
  3                455

//TEST1
NUMBER           QUANTITY         UNITPRICE
--------------------------------------------
   1                3                5
   1                3                6
   1                3                4
   2                4                8
   3                5                4

我使用了以下查询:

SELECT t.NUMBER,sum(t.TOTAL),NVL(SUM(t2.quantity*t2.unitprice),0)
FROM test t INNER JOIN test1 t2 ON t.NUMBER=t2.NUMBER
GROUP BY t.NUMBER;

输出:

NUMBER        SUM(TOTAL)      SUM(t2.quantity*t2.unitprice)
-----------------------------------------------------------
  1               474                       45               <--- only this wrong
  2               355                       32

它看起来像循环三次,所以158 * 3在记录中。

预期输出:

NUMBER        SUM(TOTAL)      SUM(t2.quantity*t2.unitprice)
-----------------------------------------------------------
 1               158                       45
 2               355                       32

2 个答案:

答案 0 :(得分:0)

这样的事情应该使用分隔总和的子查询:

select t.num,
  sum(t.total), 
  test1sum
from test t
  join (
    select num, sum(qty*unitprice) test1sum
    from test1
    group by num
    ) t2 on t.num = t2.num
group by t.num, test1sum

关于您的示例数据,您甚至可能不需要在测试总计字段上添加group by。如果该表只包含不同的ID,那么这将是相同的:

select t.num,
  t.total, 
  sum(qty*unitprice) 
from test t
  join test1 t2 on t.num = t2.num
group by t.num, t.total

答案 1 :(得分:0)

您必须了解您的加入结果是这样的:

//TEST1
NUMBER           QUANTITY         UNITPRICE             TOTAL
--------------------------------------------------------------
   1                3                5                  158
   1                3                6                  158
   1                3                4                  158
   2                4                8                  355
   3                5                4                  455

这意味着您不需要在TOTAL

上应用SUM
SELECT t.NUMBER,t.TOTAL,NVL(SUM(t2.quantity*t2.unitprice),0)
FROM test t INNER JOIN test1 t2 ON t.NUMBER=t2.NUMBER
GROUP BY t.NUMBER, t.TOTAL;
相关问题