MySql SELECT AVG的CASE语句组错误

时间:2012-10-12 19:21:11

标签: mysql select group-by case average

我正在尝试根据CASE语句使用WHERE MONTHS COUNT语句来填充单个平均值,但是它会返回无效使用组功能错误代码1111:

SELECT 
count(ORDER_NUMBER) as cnt,
a.ITEM,
MONTH(TRANS_DATE) as Month,
AVG(CASE
WHEN count(ORDER_NUMBER) IS NULL THEN 0
WHEN count(ORDER_NUMBER) < 1 AND a.CAT != 'E' THEN 0
WHEN count(ORDER_NUMBER) < 1 AND a.CAT = 'E' THEN .05
WHEN count(ORDER_NUMBER) >= 1 AND count(ORDER_NUMBER) < 4 AND a.CAT = 'E' THEN .5
WHEN count(ORDER_NUMBER) >= 4 AND a.CAT = 'E' THEN 1
WHEN count(ORDER_NUMBER) <= 5 AND a.CAT != 'E' THEN .05
WHEN count(ORDER_NUMBER) >= 6 AND count(ORDER_NUMBER) < 11 AND a.CAT != 'E' THEN .25
WHEN count(ORDER_NUMBER) >= 11 AND count(ORDER_NUMBER) < 21 AND a.CAT != 'E' THEN .5
WHEN count(ORDER_NUMBER) >= 21 AND a.CAT != 'E' THEN 1 END) as TSCORE
FROM trx.TRX_Import t2
    JOIN ATTRIBUTES a
    ON a.ITEM = t2.ITEM
WHERE `TRANS_DATE` BETWEEN DATE_SUB(CURDATE(), INTERVAL 365 DAY) AND CURDATE()
AND t2.ITEM = 'WARI-BB150'

当我添加额外的GROUP BY MONTH它正确地识别每个月TSCORE ...我宁愿它只吐出所有那些TSCORES的一个AVERAGE。

使用GROUP BY MONTH,它吐出:

   cnt     ITEM        Month   TSCORE
    1   WARI-BB150      1       0.5
    2   WARI-BB150      2       0.5
    1   WARI-BB150      3       0.5
    2   WARI-BB150      4       0.5
    2   WARI-BB150      5       0.5
    2   WARI-BB150      6       0.5
    4   WARI-BB150      7       1
    2   WARI-BB150      10      0.5
    3   WARI-BB150      11      0.5
    1   WARI-BB150      12      0.5

我希望数据只根据上表显示一个项目的平均TSCORE(所以只有一行信息):

cnt   ITEM          TSCORE
20    WARI-BB150     0.55

1 个答案:

答案 0 :(得分:4)

我必须在FROM子句中使用子查询并在其上创建AVG

SELECT
t2.ITEM as Item,
AVG(t2.TSCORE) as AvgTSCORE
FROM 
(SELECT count(ORDER_NUMBER) as cnt, t3.ITEM, MONTH(TRANS_DATE) as Month, 
(CASE
WHEN count(ORDER_NUMBER) IS NULL THEN 0
WHEN count(ORDER_NUMBER) < 1 AND a.CAT != 'E' THEN 0
WHEN count(ORDER_NUMBER) < 1 AND a.CAT = 'E' THEN .05
WHEN count(ORDER_NUMBER) >= 1 AND count(ORDER_NUMBER) < 4 AND a.CAT = 'E' THEN .5
WHEN count(ORDER_NUMBER) >= 4 AND a.CAT = 'E' THEN 1
WHEN count(ORDER_NUMBER) <= 5 AND a.CAT != 'E' THEN .05
WHEN count(ORDER_NUMBER) >= 6 AND count(ORDER_NUMBER) < 11 AND a.CAT != 'E' THEN .25
WHEN count(ORDER_NUMBER) >= 11 AND count(ORDER_NUMBER) < 21 AND a.CAT != 'E' THEN .5
WHEN count(ORDER_NUMBER) >= 21 AND a.CAT != 'E' THEN 1 END) as TSCORE
FROM trx.TRX_Import t3
JOIN ATTRIBUTES a
    ON a.ITEM = t3.ITEM
WHERE `TRANS_DATE` BETWEEN DATE_SUB(CURDATE(), INTERVAL 365 DAY) AND CURDATE()
AND t3.ITEM = 'WARI-BB150'
GROUP BY MONTH
) t2

吐出:

Item         AvgTSCORE
WARI-BB150   0.55000