这是我的表:
我想获取那些包含ServiceDescription“Plaster”或Skills“Plaster”的供应商的记录或 在“石膏”类别中,也想计算那些供应商的平均值。
注意:如果没有任何供应商的评论,那么该记录也应该来。
这是我的疑问:
select * from UserDetails u
,VendorInCategory v
,CategoryMaster c
,Review rv
where v.CategoryId=c.Id
and u.Id=r.UserId
and u.Id=rv.VendorId
and v.VendorId=u.Id
and ((u.ServiceDescription like '%Plaster%' )
or (u.Skills like '%Plaster%')
or (c.Name like '%Plaster%'))
上面的查询中的问题是我没有得到那个评论不存在的供应商。
但我也希望那个不包含评论但符合我标准的供应商。
的UserDetails:
id Servicedescription Skills
1 Plaster plaster
2 construction construvtion
3 plaster plaster
4 null null(not vendor)
5 null null(not vendor)
查看
id CustomerId Vendorid rating
1 4 1 3
2 5 1 3
预期输出:
VendorId ServiceDescription Skills averagerating
1 plaster plaster 3
3 plaster plaster 0
注意:最终输出应按平均评分的降序排列
答案 0 :(得分:3)
在这里,试试这个:
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
答案 1 :(得分:1)
许多用户已经使用 AVERAGE 函数来计算一系列数据的平均值。但是,当您拥有汇总数据而不是单个响应并需要计算平均值时,该怎么办? (例如,以5点评分标准(例如产品的评分)对选择每个评分的人数进行计数。)
如何计算加权平均值
假设您要获得每种产品的平均总体评价:
使用AVERAGE函数将导致平均值7.7 。当然,这没有任何意义。我们应该期望平均值在刻度范围内(1到5)。
为了正确计算对每个问题的平均总体回答,我们需要:
示例:
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
答案 2 :(得分:0)
使用聚合函数 AVG():
试试这个:
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;
修改强>
实现此目的的其他解决方案:
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;