2011-04-15 67 views
1

Hallo, 我有一個連接表,表tableA和tableB。 tableA有一個名爲Amount的列。 tableB有一個名爲refID的列。當refID具有相同的值時,我希望總計金額列。我是用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; 

我可以知道現在還有沒有以任何其他的解決辦法,我總金額?

THanks @!

回答

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 
+0

好一個!沒有OVER(PARTITION BY a.refId)的SUM(金額)不起作用。我正在考慮這是否是由查詢中的rank()引起的,因此我不能僅以這種方式總結數量? :0) – huahsin68 2011-04-18 05:07:09

+0

@ huahsin68:請指定「不工作」是什麼意思:它不解析,拋出錯誤,返回錯誤的結果? – Quassnoi 2011-04-18 09:32:56

2
select 
    SUM(A.Amount), 
    B.refId 
from table A 
    left outer join table B on A.refID = B.refID 
GROUP BY 
    B.refId 
0
SELECT refid, sum(a.amount) 
FROM table AS a LEFT table AS b USING (refid) 
GROUP BY refid; 
0

我有點困惑。您發佈的查詢在任何地方都沒有SUM函數,並且自行執行名爲「TABLE」的表的自聯接。我要去猜測,你實際上有兩個表(我會打電話給他們TABLE_A和表-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_B.REFID匹配TABLE_A.REFID,所以INNER JOIN將是適當的。

分享和享受。

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