【问题标题】:Error code 1111: Invalid use of group function sql错误代码1111:组函数sql的使用无效
【发布时间】:2020-07-12 07:54:12
【问题描述】:

所以我试图通过将使用的每个项目的总和乘以它们各自的价格来计算每个位置的总成本,这段代码现在可以工作:

create view location_costs as 
select
City as location, 
participant_item.SederStaple as item, 
sum(ItemAmount) as quantity,
item.ItemPrice*sum(ItemAmount) as price
from participant_item
inner join item 
on participant_item.SederStaple=item.SederStaple
group by item, location
order by location;

但我需要按位置计算所有总价格的总和,因此我将 sum 语句添加到我的代码中:

create view location_costs as 
select
City as location, 
participant_item.SederStaple as item, 
sum(ItemAmount) as quant,
sum(item.ItemPrice*sum(ItemAmount)) as price
from participant_item
inner join item 
on participant_item.SederStaple=item.SederStaple
group by item, location
order by location;

它不再工作了:

错误码1111,组函数sql使用无效

【问题讨论】:

    标签: mysql sql group-by


    【解决方案1】:

    我认为您想要在sum() 之前进行乘法:

    select City as location, pi.SederStaple as item, 
           sum(ItemAmount) as quantity,
           sum(ItemAmount * i.ItemPrice) as price
    from participant_item pi inner join
         item i
         on pi.SederStaple = i.SederStaple
    group by item, location
    order by location;
    

    请注意,我引入了表别名并将它们用于您限定的列。您应该在引用多个表的查询中限定所有列引用。

    【讨论】:

      【解决方案2】:

      不要把总和放在总和里面:

      select
        pi.City as location, 
        pi.SederStaple as item, 
        sum(pi.ItemAmount) as quant,
        sum(i.ItemPrice * pi.ItemAmount) as price
      from 
        participant_item pi
        inner join item i on pi.SederStaple = i.SederStaple
      group by pi.City, pi.SederStaple
      order by location;
      

      在整理你的别名时,我已经猜到这些东西来自哪个表(我认为一个项目不会有城市或数量,但参与者会) - 你可能需要稍微调整一下。始终为您的查询完全别名。如果将来有人将另一列添加到同名表中,它会阻止他们神秘地失败

      此外,虽然 MySQL 很乐意在其 group by 中使用别名(位置、项目),但其他数据库则不然;保留组的原始名称,以确保当您的下一份工作使用 SQL Server 时,您不会被这个仅限 mysql 的“功能”所吸引

      【讨论】:

        猜你喜欢
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 2021-11-21
        • 2011-12-20
        • 2012-07-20
        • 1970-01-01
        • 2012-12-16
        相关资源
        最近更新 更多