calculate average rating in sql server

前端 未结 3 897
耶瑟儿~
耶瑟儿~ 2021-01-14 17:52

this is my table:

\"enter

I want to fetch records of Those Vendor which contai

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 18:41

    Use aggregate function AVG():

    Try this:

    SELECT u.id, u.ServiceDescription, u.Skills, u.fullname, u.email, AVG(ISNULL(rv.rating, 0)) averagerating
    FROM UserDetails u 
    INNER JOIN VendorInCategory v ON v.VendorId=u.Id 
    INNER JOIN CategoryMaster c ON v.CategoryId=c.Id 
    LEFT JOIN Review rv ON u.Id=rv.VendorId  
    WHERE (u.ServiceDescription LIKE '%Plaster%' OR u.Skills LIKE '%Plaster%' OR 
           c.Name LIKE '%Plaster%')
    GROUP BY u.id, u.ServiceDescription, u.Skills, u.fullname, u.email
    ORDER BY averagerating DESC;
    

    EDIT

    Other solution to implement this:

    SELECT u.id, u.ServiceDescription, u.Skills, u.fullname, u.email, 
           ISNULL(rv.averagerating, 0) averagerating
    FROM UserDetails u 
    INNER JOIN VendorInCategory v ON v.VendorId=u.Id 
    INNER JOIN CategoryMaster c ON v.CategoryId=c.Id 
    LEFT JOIN (SELECT rv.VendorId, AVG(rv.rating) averagerating FROM Review rv GROUP BY rv.VendorId) rv ON u.Id=rv.VendorId  
    WHERE (u.ServiceDescription LIKE '%Plaster%' OR u.Skills LIKE '%Plaster%' OR 
           c.Name LIKE '%Plaster%')
    ORDER BY ISNULL(rv.averagerating, 0) DESC;
    

提交回复
热议问题