gpt4 book ai didi

mysql - 在多个组中按平均值计数

转载 作者:行者123 更新时间:2023-11-30 22:35:04 25 4
gpt4 key购买 nike

我有数据,其中每一行代表完整评论中的一个句子。每行都有一个分数(-1 到 1)。

从那个观点来看,我目前制作了 3 个 View ,每个 View 都有不同的分组依据,可以按天、按月或按周,并且汇总了评论的平均分数和计算其中有多少是阳性的,有多少是阴性的。

例如来自 View 的每日查询:

SELECT
`review_score_view`.`review_date` AS `review_date`,
COUNT(`review_score_view`.`review_id`) AS `review_count`,
(AVG(`review_score_view`.`score`) * 100) AS `average_score`,
SUM((CASE
WHEN (`review_score_view`.`score` >= 0) THEN 1
ELSE 0
END)) AS `positive_count`,
SUM((CASE
WHEN (`review_score_view`.`score` < 0) THEN 1
ELSE 0
END)) AS `negative_count`
FROM
`review_score_view`
GROUP BY `review_score_view`.`review_date`

我得到这样的结果:

| id  | review_date  | review_count |  average_score  | positive_count | negative_count |
|-----|--------------|--------------|-----------------|----------------|----------------|
| 521 | 2015-01-01 | 4 | -25.0000 | 2 | 2 |
| 519 | 2015-01-07 | 1 | -100.0000 | 0 | 1 |
| 518 | 2015-01-25 | 1 | 100.0000 | 1 | 0 |
| 516 | 2015-03-09 | 7 | 57.1429 | 6 | 1 |
| 515 | 2015-04-26 | 2 | -50.0000 | 1 | 1 |
| 224 | 2015-06-01 | 68 | -23.5294 | 40 | 28 |
| 222 | 2015-06-02 | 26 | -100.0000 | 1 | 25 |
| 221 | 2015-06-03 | 41 | -36.5854 | 19 | 22 |
| 220 | 2015-06-04 | 6 | -50.0000 | 2 | 4 |

问题:如何根据平均分数从这些 View 结果中进行另一个查询。对于每个结果(分数类别),基于分组依据,每月、每周或每天,我想得到这 5 个结果的总和。似乎是一件容易的事,但我无法理解它。

SUM((CASE
WHEN (average_score >= 75) THEN 1
ELSE 0
END)) AS very_positive,
SUM((CASE
WHEN (average_score between 4 and 74) THEN 1
ELSE 0
END)) AS positive,
SUM((CASE
WHEN (average_score between -5 and 5) THEN 1
ELSE 0
END)) AS neutral,
SUM((CASE
WHEN (average_score between -4 and -74) THEN 1
ELSE 0
END)) AS negative,
SUM((CASE
WHEN (average_score <= -75) THEN 1
ELSE 0
END)) AS very_negative

最后我只绘制数据。在 Excel 中制作的快速示例:

Pie

提前致谢。

最佳答案

嗯。看起来您想要行中的结果,而不是列中的结果。这表明 group by:

SELECT (CASE WHEN average_score >= 75 THEN 'VeryPositive'
WHEN average_score >= 4 THEN 'Positive'
WHEN average_score >= -5 THEN 'Neutral'
WHEN average_score >= -74 THEN 'Negative'
ELSE 'VeryNegative'
END) as ScoreGroup,
COUNT(*) as cnt
FROM dailyview v
GROUP BY ScoreGroup
ORDER BY ScoreGroup;

注意:case 返回匹配的第一个表达式,因此 between 是不必要的。

关于mysql - 在多个组中按平均值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798072/

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