我有一个查询,在下面的示例中工作正常
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
答案 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 :(得分:1)
您无法在同一级别的SELECT
中使用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;
注意:您的LEFT JOIN
是不必要的,因为WHERE
子句将其变为INNER JOIN
。所以,我将其更改为INNER JOIN
。