Sql 分区上的SUM()-聚合函数的使用无效
我有一个查询,它在下面的示例中运行良好Sql 分区上的SUM()-聚合函数的使用无效,sql,sybase-asa,Sql,Sybase Asa,我有一个查询,它在下面的示例中运行良好 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
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,如下所示,给我一个错误
“聚合函数的使用无效”
我所做的只是将RN=1添加到where语句中,我缺少什么
我正在使用Adaptive Server Anywhere 9.0,我想您需要:
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
不能在
中使用中定义的列别名,在中选择,其中
处于同一级别。这与窗口函数无关。这是所有列的规则。因此,使用子查询:
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;
注意:您的左连接
是不必要的,因为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;