我有一个Postgres图书评分表,其结构如下:
id serial primary key, userid integer not null, bookid integer not null, rating integer not null
我想提取给定用户的评分和每个其他用户的评分之间的平均差值,每个用户的评分都是单独考虑的。换句话说,作为一个用户,我想知道我的评分与某个x个用户的评分之间的平均差值是多少。最终,我希望能够将这个平均值与给定用户和被比较用户的in放在一个新的SQL表中。
我对SQL过去的简单查询相当不熟悉,我已经实现了一个在Javascript循环和SQL查询之间来回跳跃的解决方案。我正在寻找一个尽可能干净的东西,如果有人愿意帮助的话。
编辑:以下是数据和理想输出的简短示例。
id,userid,bookid,rating
1,1,1,5
2,1,2,2
3,1,3,3
4,1,4,3
5,1,5,1
6,2,1,5
7,2,2,2
8,3,1,1
9,3,2,5
10,3,3,3
下面是理想的输出,结构类似于另一个sql表:
id serial primary key,
currentuser integer not null,
compareuser integer not null,
averagediff float not null
id,currentuser,compareuser,averagediff
1,1,2,0
2,1,3,2.33333
https://stackoverflow.com/questions/47685838
复制