SQL - CHARINDEX, ltrim rtim



我正试图了解这个查询在做什么(SQL Server(:

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会从全名中找到一个空格"的索引位置,但我还没有真正理解它的最终输出是什么。

感谢所有的帮助

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

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

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

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个名称。

最新更新