MySQL将int范围(7-9)更改为值8并求平均值

时间:2013-02-10 21:45:09

标签: mysql

CREATE TABLE HrsPerWk_avg
  SELECT CrsTitle, AVG(HoursPerWkincClass)
  FROM FCQ GROUP BY CrsTitle;
  

错误代码:1292。截断错误的DOUBLE值:'7-9'

所以我想平均每周的所有时间,但我的数据是7-9,10-12等形式。我怎样才能得到平均7-9为(8)和10-12为(11)的值?

以下是数据样本:

HoursPerWkInclClass
7-9
4-6
7-9
7-9
10-12
10-12
7-9
10-12
4-6
16+

添加(8+5+8+8+11+11+8+11+5+16)=91/10=9.1

这正是我想要的。

1 个答案:

答案 0 :(得分:1)

假设您的所有范围值都是单一范围,而不是逗号分隔列表,您需要执行一些substring operations来检索-任意一侧的值并手动平均值算术。 AVG()是一个聚合函数,不能用于此目的。

CREATE TABLE HrsPerWk_avg
SELECT
  CrsTitle,
  /* Extract the min/max values with substring operations, add them, divide by 2 */
  /* SUBSTRING_INDEX() gets the first value before - */
  (SUBSTRING_INDEX(HoursPerWkincClass, '-', 1) +
  /* SUBSTR() and LOCATE() get the second value after - */
  /* Both are added and divided by 2 */
  SUBSTR(HoursPerWkincClass, LOCATE('-', HoursPerWkincClass)+1)) / 2
FROM FCQ 
GROUP BY CrsTitle

以下是一个示例:http://sqlfiddle.com/#!2/96510/2

更新

要支持上面发布的16+之类的值,您需要有条件地使用LOCATE()匹配值,并使用子字符串操作修剪+。< / p>

SELECT
  CrsTitle,
  CASE
    /* Remove + if present */
    WHEN LOCATE('+', HoursPerWkincClass) >= 1 THEN REPLACE(HoursPerWkincClass, '+', '')
    ELSE
      /* Otherwise use the range finding stuff from above... */
      (SUBSTRING_INDEX(HoursPerWkincClass, '-', 1) +
      SUBSTR(HoursPerWkincClass, LOCATE('-', HoursPerWkincClass)+1)) / 2
  END AS the_avg
FROM FCQ

http://sqlfiddle.com/#!2/bdd43/2