简体   繁体   中英

SUM() OVER PARTITION BY - Invalid use of Aggregate Function

I have a query which in the following example works fine

    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

As soon as I tell try to filter this to only show RN = 1 as shown below its give me an error of

"Invalid use of aggregate function"

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

All I have done is added is RN = 1 to the where statement, What am I missing?

I am using Adaptive Server Anywhere 9.0

I think you want:

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

You cannot use a column alias defined in a SELECT in a WHERE at the same level. This has nothing to do with window functions. It is a rule for all columns. So, use a subquery:

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;

Note: Your LEFT JOIN is unnecessary, because the WHERE clause turns it into an INNER JOIN . So, I changed it to the INNER JOIN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM