【问题标题】:What is the problem in IF statement in this code?此代码中的 IF 语句有什么问题?
【发布时间】:2020-08-31 16:16:08
【问题描述】:
select studentid,
sum(score) 'Total',
avg(IF(score>85)) 'Average',
max(score) 'Maximum',
min(score) 'Minimum'
from results
group by studentid;

错误信息:

您的 SQL 语法有错误;检查手册 对应于您的 MariaDB 服务器版本,以便使用正确的语法 ')) '平均',

max(score) '最大值',

【问题讨论】:

  • 你想做什么?
  • 有两种解决方案,但我担心你的意思是avg(IF(score>85)) 的第三件事。请解释。或者举几个例子。

标签: sql sum mariadb max average


【解决方案1】:

您没有正确使用 if() 函数 - 并且您不应该使用单引号来为结果集中的列设置别名。

你可能想要:

select 
    studentid,
    sum(score) Total,
    avg(score > 85) Average,
    max(score) Maximum,
    min(score) Minimum
from results
group by studentid;

avg(score > 85)01 之间的小数形式为您提供高于85 的分数比率。

另一方面,如果您希望平均分高于 85,您可以:

    avg(case when score > 85 then score end) Average

【讨论】:

    【解决方案2】:

    如果您希望得分比率超过 85,则使用 case 表达式:

    select studentid, sum(score) as Total,
           avg(case when score > 85 then 1 else 0 end) as ratio_over_85,
           max(score) as Maximum, min(score) as Minimum
    from results
    group by studentid;
    

    或者使用快捷方式:

           avg( score > 85 ) as ratio_over_85,
    

    另外,不要在列名中使用单引号;仅将它们用于字符串和日期常量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多