我不知道是否可能。 我有两张桌子:
医院表
中的列评分表
中的列 rating1
到rating6
是评分类型。现在按calculation
我可以从average rating
表中获取particular hospital
来自以下SELECT查询
ratings
以上查询对我来说非常合适,但是SELECT IFNULL((SUM(charges) + SUM(behaviour) + SUM(admission) + SUM(properInformation)
+ SUM(hygine) + SUM(treatment))/(count(hospitalID) * 6), 0
) AverageRating,COUNT(ID) RatingCount
FROM ratings
WHERE hospitalID = '111111'
我还想在我的医院餐桌上计算,因为我想对医院进行排名。
mySQL中是否有任何函数可以通过引用评级表来计算医院表的平均评分。
答案 0 :(得分:3)
根据给定的表结构,您可以尝试这个。
修改强>
SELECT avgratings.*, @curRow := @curRow + 1 AS hospitalRank
FROM (
SELECT (SUM(r.`rating1`)+SUM(r.`rating2`)+SUM(r.`rating3`)+SUM(r.`rating4`)+SUM(r.`rating5`)+SUM(r.`rating6`))/(COUNT(r.`hospitalID`)*6) AS AverageRating, h.hospitalID
FROM hospitals h INNER JOIN ratings r
ON h.`hospitalID`=r.`hospitalID`
WHERE 1 GROUP BY r.`hospitalID`
) avgratings JOIN (SELECT @curRow := 0) rank
ORDER BY avgratings.AverageRating DESC
第二次查询以获得特定医院的排名。
SELECT tablea.*
FROM (
SELECT avgratings.*, @curRow := @curRow + 1 AS hospitalRank
FROM (
SELECT (SUM(r.`rating1`)+SUM(r.`rating2`)+SUM(r.`rating3`)+SUM(r.`rating4`)+SUM(r.`rating5`)+SUM(r.`rating6`))/(COUNT(r.`hospitalID`)*6) AS AverageRating, h.hospitalID
FROM hospitals h INNER JOIN ratings r
ON h.`hospitalID`=r.`hospitalID`
WHERE 1 GROUP BY r.`hospitalID`
) avgratings JOIN (SELECT @curRow := 0) rank
) tablea
WHERE tablea.hospitalID=1 ORDER BY tablea.AverageRating DESC
将1
块中的WHERE
替换为hospitalID
。
答案 1 :(得分:1)
我不确定我理解你的问题......
您可以获得单个记录的平均值:
charges + behaviour + admission + properInformation + hygine + treatment / 6
你得到了总的平均值:
avg(charges + behaviour + admission + properInformation + hygine + treatment / 6)
我命令每个医院得到它,你按医院分组:
select
hospitalid,
avg(charges + behaviour + admission + properinformation + hygine + treatment / 6) as avr,
count(*) as rating_count
from ratings
group by hospitalid
order by 2 desc;
您可以通过加入医院表来选择医院数据(例如医院名称)。 E.g。
select
h.hospitalid,
h.name,
avg(r.charges + r.behaviour + r.admission +
r.properinformation + r.hygine + r.treatment / 6) as average_rating,
count(*) as rating_count
from hospitals h
left join ratings r on r.hospitalid = h.hospitalid
group by h.hospitalid
order by average_rating desc;