MYSQL SUM()返回前10个值

时间:2011-08-21 18:08:55

标签: mysql database select sum

我试图找到7个数字字段的SUM来查找总数,COMBINED和输出一起显示LIMIT为10个结果ORDER BY每个SUM的总和。

这是我的SUM代码,它本身可以工作,但我不确定如何将两个查询一起使用,不断出现语法错误。

SUM(comfort + service + ambience + friendliness + spacious + experience + toilets)/(7)/COUNT(shop_id) AS total FROM ratings GROUP BY shop_id

这是我正常返回数据的SQL查询:

SELECT * FROM pubs, services, ratings
WHERE pubs.shop_id=services.shop_id AND pubs.shop_id=ratings.shop_id
GROUP BY shop_name
ORDER BY shop_name ASC

我没有存储在我的数据库中的7个值的总数,我使用上面的SUM查询来查找总数。感谢

1 个答案:

答案 0 :(得分:1)

尝试使用

SELECT pubs.*, services.*, sum(temp.total) as final_total FROM pubs inner join services on pubs.shop_id=services.shop_id
inner join (
select 
SUM(comfort + service + ambience + friendliness + spacious + experience + toilets)/(7) /COUNT(shop_id) AS total, shop_id FROM ratings GROUP BY shop_id
) as temp on pubs.shop_id=temp.shop_id
GROUP BY shop_name
ORDER BY final_total DESC, shop_name ASC