示例数据: 5 W3 a# v0 B; M6 P2 Itable A9 ?# W# D: b7 G$ Z% b
part rating numReviews7 w9 ?# j; j% Z' k0 e
A308 100 7% }8 ~9 o# A) k1 r0 e
A308 98 89 8 U1 q( q+ U+ H' e5 R G" [我正在尝试获得上述数据的平均评分。- d2 y* t$ ]7 b3 P3 {
它需要的是每行rating*的总和numReviews除以总数numReviews 9 C, Y3 m9 n/ c$ t- N0 W; T这是我正在尝试的操作,但给出的结果不正确(49.07,应为98.15):0 W! ?: I1 N! Y Q- r) j
select part, ( r d6 H# `2 s; d% D8 P8 y
cast((AVG(rating*numReviews)/sum(numReviews)) as decimal(8,2)) as rating_average7 b' `1 E: Q4 T! u
from A group by part order by part- s) X: f1 j: j `
可以在单个查询中完成吗?我正在使用SQL Server0 D' ^; ]/ H* W6 U1 D) J
9 m; e, t3 ~5 E4 W 解决方案: * C& `+ ?5 c2 Z! X1 C8 K ! c( o W5 g& M r; e( K6 a
, I) c& C6 Z( P" |5 H
* P. ]* W& t7 w/ B0 `! k 只需回到加权平均的定义即可,因此使用sum()s和除法: 8 U" F/ _. ]$ T {6 eselect part, sum(rating * numreviews) / sum(numreviews) as rating_average . |' E& I7 Q D ~4 ~/ Bfrom a5 J/ ], i7 M; A0 B9 w: R2 V
group by part ) s# u, F6 U/ [2 Q$ m. m# Dorder by part;. \0 ~/ n2 V) ~1 m. w2 m
如果愿意,可以将其转换为小数:! n) \2 ~( N: R& L, x
select part, 4 I' _ J' |$ i& h; d+ t cast(sum(rating * numreviews) / sum(numreviews) as decimal(8, 2)) as rating_average. _# h6 e2 r: S3 _7 D
from a - `# h# u: [. ^group by part1 N2 T9 M) b) x4 ?, [. ^2 M+ `, x
order by part;