简体   繁体   English

计算加权平均值?

[英]Calculating a weighted average?

ProductData产品数据

Respondant受访者 ProductNo产品编号
1 1 Chips筹码
2 2 Fish
3 3 Chips筹码
4 4 Fish

ConsumerData消费者数据

Respondant受访者 Demographics人口统计 Weight重量
1 1 87 87 34 34
2 2 16 16 432 432
3 3 34 34 54 54
4 4 56 56 212 212

ScoreData分数数据

Respondant受访者 Date日期 Score分数
1 1 2022-03-03 2022-03-03 4 4
2 2 2022-03-03 2022-03-03 8 8
3 3 2022-03-03 2022-03-03 3 3
4 4 2022-03-03 2022-03-03 2 2

Input data available involves ratings given by respondents to products.可用的输入数据涉及受访者对产品的评级。 The three input tables each store information related to the product, the respondent and the score given by respondents to products in specific days.三个输入表分别存储与产品、受访者相关的信息以及受访者在特定日期对产品给出的分数。 The " Respondent " field of each table is used to match the three tables.每个表的“ Respondent ”字段用于匹配三个表。

What I need is computing an average rating for each product, weighted by each respondent weight.我需要的是计算每个产品的平均评分,按每个受访者的体重加权。

I can't seem to get the weight to work.我似乎无法让体重发挥作用。 So far I've got this.到目前为止,我已经得到了这个。

SELECT SUM(ScoreData.score * ConsumerData.weight) / SUM(ConsumerData.weight) AS AverageRating
FROM      ScoreData  
LEFT JOIN ConsumerData     
       ON ScoreData.respondantID = ConsumerData.respondantID     
WHERE date = '2022-04-05'

This seems to be returning nothing even though both tables have integers in them to get the weight.即使两个表中都有整数来获得权重,这似乎也没有返回任何内容。 Its not returning null, there is just nothing being placed into the table.它没有返回 null,表中没有任何内容。

Any help is appreciated, thanks.任何帮助表示赞赏,谢谢。

As already suggested in the comments by @Jan, the empty output you get may be related to the filtering operation you carry out on the date ( WHERE date = '2022-04-05' ), which would result in no rows in case no respondent has rated any product in that specific day.正如@Jan 的评论中已经建议的那样,您获得的空 output 可能与您在日期( WHERE date = '2022-04-05' )执行的过滤操作有关,如果没有,这将导致没有行受访者在该特定日期对任何产品进行了评级。

There are a couple of issues in your query:您的查询中有几个问题:

  • you don't have references to the products table, you need to add one further join operation to have full information您没有对 products 表的引用,您需要再添加一个连接操作以获得完整信息
  • when you apply aggregate functions like SUM and you want to partition the aggregation on different products, you need to add a GROUP BY clause, which contains the partitioning field当您应用SUM之类的聚合函数并且想要对不同产品的聚合进行分区时,您需要添加一个GROUP BY子句,其中包含分区字段
SELECT p.ProductNo,
       SUM(c.Weight * s.Score) / SUM(c.weight) 
FROM       ProductData  p
INNER JOIN ConsumerData c
        ON p.Respondant = c.Respondant
INNER JOIN ScoreData    s
        ON p.Respondant = s.Respondant
GROUP BY p.ProductNo

Check the demo here .此处查看演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM