this is my table:
I want to fetch records of Those Vendor which contai
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;
Many users have used the AVERAGE function to calculate the average of a series of data. But what do you do when you have summary data instead of individual responses and need to calculate an average? (For example, counts of the number of people who selected each rating on a 5-point rating scale like the rating of a product.)
How to Calculate a Weighted Average
Let’s say you want to get the average overall rating for each product:
Using the AVERAGE function would result in an average of 7.7. Of course, this doesn’t make any sense. We should expect an average within the range of the scale (1 to 5).
In order to correctly calculate the average overall response to each question, we need to:
Example:
SELECT
SUM(
case
WHEN FLOOR(rating) = 1 THEN rating
WHEN FLOOR(rating) = 2 THEN rating *2
WHEN FLOOR(rating) = 3 THEN rating *3
WHEN FLOOR(rating) = 4 THEN rating *4
WHEN FLOOR(rating) = 5 THEN rating *5
end
) / SUM(rating)
FROM tableRatings
Here, try this:
create table UserDetails(
Id int,
ServiceDescription varchar(20),
Skills varchar(20)
)
create table Review(
Id int,
CustomerId int,
VendorId int,
Rating int
)
insert into UserDetails values(1, 'Plaster', 'plaster'),(2, 'construction', 'construction'),(3, 'plaster', 'plaster');
insert into Review values(1, 4, 1, 3),(2, 5, 1, 3);
select
u.Id as VendorId,
u.ServiceDescription,
u.Skills,
isnull(sum(r.rating)/count(r.rating), 0) as AverageRating
from UserDetails u
left join Review r
on r.VendorId = u.id
where
u.ServiceDescription like '%plaster%'
or u.Skills like '%plaster%'
group by
u.Id,
u.ServiceDescription,
u.Skills
order by AverageRating desc