2

我正在尝试根据使用带有 a 的子句的语句填充单个平均值,但是CASE它返回对组函数错误代码 1111 的无效使用:WHEREMONTHSCOUNT

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...我宁愿它只是吐出所有这些 TSCORE 的一个平均值。

随着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(所以只有 1 行信息):

cnt   ITEM          TSCORE
20    WARI-BB150     0.55
4

1 回答 1

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
于 2012-10-12T20:05:07.890 回答