我有一个 mysql 表,其中存储了客户端的星级,所以:
参考,客户代码,日期,评论,星星
相同的客户端代码可以出现多次。
我需要选择具有最高平均星数的不同客户端代码。任何建议如何得到这个
SELECT
t1.clientcode clientcode,
t2.sum sum,
t3.count count,
CASE t3.count WHEN 0 THEN 0 ELSE t2.sum / t3.count END average
FROM
t1
LEFT JOIN
(
SELECT
clientcode,
SUM(stars) sum
FROM t1
GROUP BY clientcode
) t2 ON t1.clientcode = t2.clientcode
LEFT JOIN
(
SELECT
clientcode,
COUNT(stars) count
FROM t1
GROUP BY clientcode
) t3 ON t1.clientcode = t3.clientcode
Please try query given below.
select avg(`stars`) AS `avgstar` ,`clientcode` from `t1` group by `clientcode` order by `avgstar` DESC
Here group by clientcode
will be get record for every distinct clientcode
and order by avgstar
where avgstar is average of stars field value for each clientcode
in Descinding order.
thanks
这将显示不同客户端代码的星级平均值
SELECT avg(stars) from t1 group by clientcode;
SELECT
t1.*
FROM
table t1
WHERE
t1.stars IN
(
SELECT
MAX(t2.stars)
FROM
table t2
WHERE
t2.clientcode = t1.clientcode
)