2015-06-09 64 views
1

的我有一個查詢這在下面的例子當我告訴嘗試這個過濾器,只顯示RN = 1所示工作正常SUM()OVER PARTION BY - 無效使用聚合函數

Select t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 
    , sum(t1.qty/100) 
    , ROW_NUMBER() Over (Partition By t2.leadno order by sum(qty/100) desc) as RN 
From dba.quotelne as t1 
    LEFT JOIN dba.quotehdr as t2 ON t1.quoteno = t2.quoteno 
Where leadno = 31665 
    and t1.statusflag = 'A' 
    and t2.statusflag = 'A' 
Group By t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 

低於其給我的

「無效使用集合函數」

Select t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 
    , sum(t1.qty/100) 
    , ROW_NUMBER() Over (Partition By t2.leadno order by sum(qty/100) desc) as RN 
From dba.quotelne as t1 
    LEFT JOIN dba.quotehdr as t2 ON t1.quoteno = t2.quoteno 
Where leadno = 31665 
    and t1.statusflag = 'A' 
    and t2.statusflag = 'A' 
    and RN = 1 
Group By t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 

錯誤我所做的所有添加的是RN = 1到where語句,我錯過了什麼?

我使用Adaptive Server Anywhere 9.0

回答

1

我想你想:

Select Top 1 t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 
    , sum(t1.qty/100) 
    , ROW_NUMBER() Over (Partition By t2.leadno order by sum(qty/100) desc) as RN 
From dba.quotelne as t1 
    LEFT JOIN dba.quotehdr as t2 ON t1.quoteno = t2.quoteno 
Where leadno = 31665 
    and t1.statusflag = 'A' 
    and t2.statusflag = 'A' 
Group By t2.leadno 
    , t1.quoteno 
    , t1.cn_ref 
Order By RN 
1

你不能在同一水平的WHERE使用在SELECT定義的列別名。這與窗口函數無關。這是所有列的規則。因此,使用子查詢:

select t.* 
from (Select t2.leadno, t1.quoteno, t1.cn_ref, sum(t1.qty/100), 
      ROW_NUMBER() Over (Partition By t2.leadno order by sum(qty/100) desc) as RN 
     From dba.quotelne t1 INNER JOIN 
      dba.quotehdr t2 
      ON t1.quoteno = t2.quoteno 
     Where leadno = 31665 and t1.statusflag = 'A' and t2.statusflag = 'A' 
     Group By t2.leadno, t1.quoteno, t1.cn_ref 
    ) t 
where rn = 1; 

注意:您LEFT JOIN是不必要的,因爲WHERE條款把它變成一個INNER JOIN。所以,我把它改成了INNER JOIN