如何在有联接表时查询总计

时间:2011-04-15 10:50:26

标签: sql sum

喂, 我有一个连接表,表示tableA和tableB。 tableA有一个名为Amount的列。 tableB有一个名为refID的列。当refID具有相同的值时,我想总计Amount列。我在查询中使用SUM,但它给我一个错误:

ORA-30483: window  functions are not allowed here
30483. 00000 -  "window  functions are not allowed here"
*Cause:    Window functions are allowed only in the SELECT list of a query.
           And, window function cannot be an argument to another window or group
           function.

以下是我的查询供您参考:

select *
from (
       select SUM(A.Amount), B.refId, Rank() over (partition by B.refID order by B.id desc) as ranking
       from table A
       left outer join table B on A.refID = B.refID
)
where ranking=1;

我可以知道是否有任何替代解决方案让我按金额计算?

谢谢@!

5 个答案:

答案 0 :(得分:2)

select 
  SUM(A.Amount), 
  B.refId
from table A
  left outer join table B on A.refID = B.refID
GROUP BY 
  B.refId

答案 1 :(得分:1)

SELECT  *
FROM    (
        SELECT  A.Amount, B.refId,
                Rank() over (partition by A.refID order by B.id desc) as ranking,
                SUM(amount) OVER (PARTITION BY a.refId) AS asum
        FROM    tableA A
        LEFT JOIN
                tableB B
        ON      B.refID = A.refID
        )
WHERE   ranking = 1

答案 2 :(得分:1)

  Declare @T table(id int) 
    insert into @T values (1),(2)
  Declare @T1 table(Tid int,fkid int,Amount int)
    insert into @T1 values (1,1,200),(2,1,250),(3,2,100),(4,2,25)

    Select SUM(t1.Amount) as amount,t1.fkid as id from @T t
 left outer join @T1 t1 on t1.fkid = t.id group by t1.fkid

答案 3 :(得分:0)

SELECT refid, sum(a.amount)
FROM table AS a LEFT table AS b USING (refid)
GROUP BY refid;

答案 4 :(得分:0)

我有点困惑。您发布的查询在任何地方都没有SUM函数,并执行了一个名为“TABLE”的表的自连接。我猜你实际上有两个表(我将它们称为TABLE_A和TABLE_B),在这种情况下,下面应该这样做:

SELECT a.REFID, SUM(a.AMOUNT)
  FROM TABLE_A a
  INNER JOIN TABLE_B b
    ON (b.REFID = a.REFID)
  GROUP BY a.REFID;

如果我理解了您的问题,那么当您拥有与TABLE_A.REFID匹配的TABLE_B.REFID时,您只需要结果,因此INNER JOIN将是合适的。

分享并享受。