我发现的搜索结果与我正在尝试执行的搜索结果大不相同。我很确定我正在重新思考。任何帮助或指针,将不胜感激。我正在使用mssql和sql server 2012子查询中的SQL AVG - 导致“子查询返回的值超过1”。
我有一个表有3列 - document_id,member_id和rating。我想平均表中所有匹配的document_id的评分。
这里的整个过程 - 但块之后,我会专注于脏的部分:
select @title = title,
@description = document.[description],
@authors = authors,
@create_date = case when create_date is null then null else convert(varchar(10),create_date, 101) end,
@revision_date = case when revision_date is null then null else convert(varchar(10),revision_date, 101) end,
@file_format_id = document.file_format_id,
@document_category_id = document.document_category_id,
@size = [size],
@document_key = document_key,
@visibility = document.visibility,
@upload_member_id = upload_member_id,
@calculated_rating = case when document_category.allow_member_ratings = 1 then (select avg(convert(decimal,rating)) from document_rating where [document].document_id = document_rating.document_id) else null end,
@member_rating = case when (document_category.allow_member_ratings = 1) then (select convert(decimal,rating) from document_rating where [document].document_id = document_rating.document_id) else null end
from club.dbo.document
inner join club.dbo.document_category
on (document.document_category_id = document_category.document_category_id)
inner join club.dbo.file_format
on (document.file_format_id = file_format.file_format_id)
where document_id = @document_id
and document_category.club_id = @club_id
的的一部分,这给我的错误是在@calculated_rating输出参数的子查询。
@calculated_rating = case when document_category.allow_member_ratings = 1
then (select avg(convert(decimal,rating))
from document_rating
where [document].document_id = document_rating.document_id)
else null end,
在上述结果“子查询返回多个值,这是当子查询跟随不允许=,!=,<,”如果一个DOCUMENT_ID有超过1次等级进入,PROC炸弹。显而易见的是,特定document_id的所有评级的总和不会被添加/平均。
所以 - 我想是这样的:
@calculated_rating = case when document_category.allow_member_ratings = 1 then
(SELECT AVG(convert(decimal,document_rating.rating))
FROM(SELECT SUM(document_rating.rating) rating
FROM document_rating
WHERE [document].document_id = document_rating.document_id
GROUP BY document_rating.document_id) else null end,
有在那里,因为我做了一个烂摊子一个语法错误 - 但我应该在这里使用别名?我试图做甚至可能吗?
解决
问题是不是跟一般 - 但与成员等级。需要为where语句添加额外限制。
@member_rating = case when (document_category.allow_member_ratings = 1) then (select convert(decimal,rating) from document_rating where @member_id = document_rating.member_id and [document].document_id = document_rating.document_id) else null end
第二组的眼睛是真正有用的时候。感谢您指出这一点,这是在子查询中的错误。我需要在“where”语句中添加一个额外的限制,并为过程添加一个附加参数。编辑我的问题。解决。再次感谢 – apoji187