SQL - CHARINDEX,ultrim rtim

SQL - CHARINDEX, ltrim rtim

我正在尝试了解此查询的作用(SQL 服务器):

Select StudentId, left(fullname,charindex(' ',fullname + ' ')) as mysteryCol
From (select StudentId, ltrim (rtrim (fullname)) as fullname from STUDENTS) as S

以及查询:

Select top 10 msyteryCol , count(*) as howMany from
(Select left (fullname, charindex (' ', fullname + ' ')) as mysteryCol
From (select StudentId, ltrim (rtrim (fullname)) as fullname from STUDENTS) as S) as Z
Group by mysteryCol
Having count (*) > 100
Order by 2 desc

我只知道charindex会从全名中找到一个空的space ' '的索引位置,但我还没有真正理解这个最终输出是什么。

感谢大家的帮助

简答:它将从全名中读取名字。第二个查询将仅根据名字进行分组,并给出前 10 个名字,并按降序排列出现次数超过 100 次的计数。

解释:From (select StudentId, ltrim (rtrim (fullname)) as fullname from STUDENTS 这行代码删除了全名中所有前导和尾随的 space。名字中只剩下 space 现在留在名字和姓氏之间(如果有的话)。

charindex(' ',fullname + ' ') 此行获取全名中出现的第一个 space 的索引。如果全名仅由一个字符串组成,fullname + ' ' 会处理这个问题。这为我们提供了名称中出现的第一个 space 的索引。 left(fullname,charindex(' ',fullname + ' ')) 获取第一次出现的 space 字符左侧的字符串值。因此名字。

Select top 10 msyteryCol , count(*) as howMany from
(Select left (fullname, charindex (' ', fullname + ' ')) as mysteryCol
From (select StudentId, ltrim (rtrim (fullname)) as fullname from STUDENTS) as 
S) as Z
Group by mysteryCol
Having count (*) > 100
Order by 2 desc

此查询按名字对查询进行分组,并计算每个名字的出现次数。它显示次数最多且出现次数大于 100 的前 10 个名称。