解决SUM和AVG,无法对包含聚集或子查询的表达式执行聚集功能

时间:2019-02-04 15:24:14

标签: sql sql-server

我在SQL中有以下查询以求和和平均值:

USE DBSTG_INT
GO

select distinct 
sum(a.EventoPrecioReg) as PrecioRegular,
sum(a.EventoPrecioVta) as PrecioVenta,
AVG(VTA_IUnidades) as Unidades,
SUM((a.EventoPrecioVta - a.EventoPrecioReg) * (AVG(VTA_IUnidades))) as Inversion
from EventoPrecioDeta a WITH (NOLOCK)

当我执行它时,它显示以下问题:

  

第15层,州1,第8行的消息130
    无法对包含聚合或子查询的表达式执行聚合功能。

我做错了什么以及如何解决?

2 个答案:

答案 0 :(得分:1)

select distinct在这种情况下没有意义。您的问题是嵌套聚合。也许您打算:

select sum(a.EventoPrecioReg) as PrecioRegular,
       sum(a.EventoPrecioVta) as PrecioVenta,
       AVG(VTA_IUnidades) as Unidades,
       SUM(a.EventoPrecioVta - a.EventoPrecioReg) * AVG(VTA_IUnidades) as Inversion
from EventoPrecioDeta a ;

答案 1 :(得分:1)

像下面一样尝试

select  
sum(a.EventoPrecioReg) as PrecioRegular,
sum(a.EventoPrecioVta) as PrecioVenta,
AVG(VTA_IUnidades) as Unidades,
SUM(a.EventoPrecioVta - a.EventoPrecioReg) * AVG(VTA_IUnidades) as Inversion
from EventoPrecioDeta a