2015-06-09 47 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