我的SQL - 从另一个表行引用数据

时间:2016-04-30 05:04:25

标签: mysql sql

我不知道是否可能。 我有两张桌子:

医院

中的列
  • hospitalID
  • 名称
  • AverageRating

评分

中的列
  • ID
  • 额定值1
  • rating2
  • rating3
  • rating4
  • rating5
  • rating6
  • hospitalID

rating1rating6是评分类型。现在按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中是否有任何函数可以通过引用评级表来计算医院表的平均评分。

评级表 enter image description here

查询输出表 enter image description here

2 个答案:

答案 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;