【问题标题】:How to do conditional average?如何进行条件平均?
【发布时间】:2014-03-02 15:24:31
【问题描述】:

我想计算 post_author 的平均结果。这是我的代码:

AVG(CASE WHEN post_author = 1 THEN post_content ELSE 0 END )as avg

在 2 条记录 (100, 66.7) 上得到 100 的结果,应该是 83.35 哪里出了问题?

【问题讨论】:

  • post_auther 和 post_content 是数字列吗?
  • 使用group by post_author 进行avg 计算有什么问题?
  • 考虑提供适当的 DDL(和/或 sqlfiddle)以及所需的结果集
  • post_auther 是数字,post_content 不是。 @Ravinder --我需要按其他东西分组。
  • 如果post_content不是数字,那你为什么用它来计算avg

标签: mysql sql average


【解决方案1】:

你可以去掉else子句,所以NULL被传入:

AVG(CASE WHEN post_author = 1 THEN post_content END) as "avg"

您的查询将不匹配的值设置为 0 以求平均值。你希望它们被忽略,所以使用NULL

【讨论】:

  • AVG(CASE WHEN post_author = 1 THEN post_content ELSE NULL END )as avg 可以更清楚
猜你喜欢
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多