mysql使用where条件和连接查询选择多个avg列

时间:2018-04-21 06:20:43

标签: mysql

如何使用此查询的条件?比如,WHERE institutions.instituteId IN(“1”,“2”,“4”,“15”)。

SELECT (SELECT avg(rating_score.score) FROM reviews INNER JOIN rating_score ON  reviews.reviewsId=rating_score.reviewsId WHERE reviews.instituteId='13' AND ratingItemId='1') as 'Acadamics', 
(SELECT avg(rating_score.score) FROM reviews INNER JOIN rating_score ON reviews.reviewsId=rating_score.reviewsId WHERE reviews.instituteId='13' AND ratingItemId='2') as 'Area_of_study',
(SELECT avg(rating_score.score) FROM reviews INNER JOIN rating_score ON reviews.reviewsId=rating_score.reviewsId WHERE reviews.instituteId='13' AND ratingItemId='3') as 'Campus_Facilities', 
(SELECT avg(rating_score.score) FROM reviews INNER JOIN rating_score ON reviews.reviewsId=rating_score.reviewsId WHERE reviews.instituteId='13' AND ratingItemId='4') as 'Acommadatoin',
(SELECT avg(rating_score.score) FROM reviews INNER JOIN rating_score ON reviews.reviewsId=rating_score.reviewsId WHERE reviews.instituteId='13' AND ratingItemId='5') as 'Sports_Facilities',
institutions.instituteId, institutions.instituteName, institutions.location, countries.countryName, institutions.siteAddress, institutions.overallRatings FROM institutions INNER JOIN countries ON institutions.countryId=countries.countryId 
WHERE institutions.instituteId='13'

1 个答案:

答案 0 :(得分:1)

这与need to return two sets of data with two different where clauses中的解决方案类似,但使用AVG代替SUM。主要区别在于您不在ELSE 0中使用CASE,因为您不希望对具有不同0的所有行平均raingItemIdAVG()将忽略这些空行。

SELECT 
    AVG(CASE WHEN ratingItemId='1' THEN rs.score END) AS Academics,
    AVG(CASE WHEN ratingItemId='2' THEN rs.score END) AS Area_of_study,
    AVG(CASE WHEN ratingItemId='3' THEN rs.score END) AS Campus_Facilities,
    AVG(CASE WHEN ratingItemId='4' THEN rs.score END) AS Acommadatoin,
    AVG(CASE WHEN ratingItemId='5' THEN rs.score END) AS Sports_Facilities,
    i.instituteName, i.location, c.countryName, i.siteAddress, i.overallRatings
FROM institutions AS i
INNER JOIN countries AS c ON i.countryId=c.countryId
LEFT JOIN reviews AS r ON r.instituteId = i.instituteId
LEFT JOIN rating_score AS rs ON rs.reviewsId = r.reviewsId
WHERE i.instituteId IN (1, 2, 4, 15)
GROUP BY i.instituteId