我试图选择一个具有字符最大数量的记录,例如' A'并得到此错误"无法对包含聚合或子查询的表达式执行聚合函数。"。造成这种情况的原因是什么,如何纠正呢。谢谢!
select
*
from GROUPS as G
inner join STUDENT_GROUP as SG
on sg.Group_ID = g.Groups_ID
inner join STUDENT as S
on s.Student_ID = sg.Student_ID
inner join STUDENT_MARKS as SM
on SM.Student_ID=s.Student_ID
inner join smark as m
on m.mark_id=sm.Mark_ID
where m.Mark_name = max(count('A'));
答案 0 :(得分:1)
没有这样的函数可以计算特定字符在字符串中出现的次数,但是您可以在删除此特定字符后使用原始字符串的长度和字符串的长度,如下所示:
declare @foo nvarchar(max)
set @foo='abcabc'
select len(@foo)-len(replace(@foo,'a','')) as [Total of 'a']
在您的情况下,使用TOP 1
将按特定顺序显示第一行,此顺序为字符A
的计数
select top 1 *
from GROUPS as G
inner join STUDENT_GROUP as SG
on sg.Group_ID = g.Groups_ID
inner join STUDENT as S
on s.Student_ID = sg.Student_ID
inner join STUDENT_MARKS as SM
on SM.Student_ID=s.Student_ID
inner join smark as m
on m.mark_id=sm.Mark_ID
order by
len(m.Mark_name)-len(replace(m.Mark_name,'A','')) DESC
正如@jyao所说,如果你需要获得具有相同最大字符数量的所有记录,请使用TOP 1 WITH TIES
:
select top 1 with ties *
...