sql avg比较表现不尽如人意

时间:2016-11-10 00:29:52

标签: mysql aggregate-functions having

我试图通过使用

行过滤掉所有正平均值
 HAVING AVG(blurt_analysis.sentiment) < 0 

然而由于意外的原因,这一行没有按预期进行,实际上是让我的查询没有返回任何内容并且我很难弄清楚为什么我的查询看起来像

SELECT topic.id,topic.description,blurt.location,count(blurt.blurtid)as 'number of blurts',AVG(blurt_analysis.sentiment) as avgSentiment
FROM topic, blurt_analysis,blurt
WHERE topic.id=blurt_analysis.topicid AND blurt.blurtid = blurt_analysis.blurtid AND blurt.email = blurt_analysis.email 
group by blurt.location,topic.id
HAVING AVG(blurt_analysis.sentiment) < 0 

如果没有有线,则返回看起来像这样,并且行

是空的
1   shoes   California  2   2.5000
2   speaker California  3   1.3333
3   bats    California  3   1.0000
4   hoodies California  2   -0.5000
5   caps    California  1   -2.0000
6   pens    California  2   0.0000
7   games   California  4   1.2500
1   shoes   Colarado    1   1.0000
2   speaker Colarado    3   1.6667
3   bats    Colarado    1   1.0000
5   caps    Colarado    1   3.0000
7   games   Colarado    1   1.0000

第一列是topicid,第二列是主题描述,第三列是脱口语位置,第四列是脱口秀,第五列是平均情绪(我想尝试过滤正数)

更新我仍然没有设法弄清楚为什么查询不起作用但我设法过滤正数与另一个添加使我的SQL看起来像

SELECT topic.id,topic.description,blurt.location,count(blurt.blurtid)as 'number of blurts',AVG(blurt_analysis.sentiment) as avgSentiment
FROM topic, blurt_analysis,blurt
WHERE topic.id=blurt_analysis.topicid AND blurt.blurtid = blurt_analysis.blurtid AND blurt.email = blurt_analysis.email AND blurt_analysis.sentiment <0
group by blurt.location,topic.id,topic.description

2 个答案:

答案 0 :(得分:0)

您是否尝试使用NVL或CASE替换空值?它曾经为我工作过一次。

即:AVG(NVL(blurt_analysis.sentiment,0))

答案 1 :(得分:0)

你很幸运;现在你不走运了。 heroku repo:reset 子句中的每个非聚合列都必须出现在select中。快速浏览显示group by是缺失的。

显然MySQL容忍了您的原始查询,但是当您添加了HAVING时,它就会失败。或者你得到了不确定的结果;我不知道。但我敢打赌,如果你更正了你的查询,你的HAVING子句会表现得更好。 :-)