1

我有一个查询,在以下示例中可以正常工作

    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

一旦我告诉尝试过滤它以仅显示 RN = 1 如下所示,它会给我一个错误

“无效使用聚合函数”

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

4

2 回答 2

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
于 2015-06-09T10:59:52.153 回答
1

您不能在同一级别使用在 aSELECT中定义的列别名。WHERE这与窗口函数无关。这是所有列的规则。因此,使用子查询:

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;

注意: YourLEFT JOIN是不必要的,因为该WHERE子句将它变成了INNER JOIN. 所以,我把它改成了INNER JOIN.

于 2015-06-09T11:00:13.343 回答