gpt4 book ai didi

MySql SELECT AVG of CASE语句组错误

转载 作者:行者123 更新时间:2023-11-29 01:43:43 25 4
gpt4 key购买 nike

我正在尝试根据 CASE 语句使用 WHERE 子句和 COUNT< 的 MONTHS 来填充单个平均值,但是它返回组函数错误代码 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 的一个平均值。

使用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

最佳答案

我必须在 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

关于MySql SELECT AVG of CASE语句组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com