1

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jonathan Griffin
  • 148
  • 2
  • 17

2 Answers2

1

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
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
1

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786