【问题标题】:Solve on SUM and AVG, Cannot perform an aggregate function on an expression containing an aggregate or a subquery解决 SUM 和 AVG,无法对包含聚合或子查询的表达式执行聚合函数
【发布时间】:2019-02-04 15:24:14
【问题描述】:

我在 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)

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

消息 130,第 15 级,状态 1,第 8 行
无法对包含聚合或子查询的表达式执行聚合函数。

我做错了什么,我该如何解决?

【问题讨论】:

  • 您是否可能只是混淆了括号? SUM(a.EventoPrecioVta - a.EventoPrecioReg) * AVG(VTA_IUnidades) as Inversion

标签: sql sql-server


【解决方案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 ;

【讨论】:

    【解决方案2】:

    像下面这样尝试不需要不同的

    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
    

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多