使用“group by”查找计数

5
我有一个如下的学生表。
Rajesh Kumar
Nagendra Prasad
Bharath kumar
Raghav Kumar
Abhnav Bindhra

我需要编写一个查询,以统计名字包含“kumar”和“Prasad”的学生人数。
Kumar   3
Prasad  1

我该怎么做?我尝试使用以下查询,但对于groupby子句应放什么表示怀疑?

 Select Name,count(Name) from Student where 
    Name LIKE  ('%Kumar%')
    or Name LIKE  ('%Prasad%')
    group by ???

4
可能是T-SQL-使用LIKE进行GROUP BY-是否可行?的重复问题。 - default locale
4个回答

6
select  FindName 
,       count(*)
from    (
        select  case
                when Name like '%Kumar%' then 'Kumar'
                when Name like '%Prasad%' then 'Prasad'
                end as FindName
        from    Student
        ) as SubQueryAlias
where   FindName is not null
group by
        FindName

2
您可以尝试以下SQL查询语句:
select SUBSTRING(name, CHARINDEX(' ', name) + 1, LEN(name)) as lname, count(name)
from Student
where name like '%kumar%' or name like '%Prasad%'
group by SUBSTRING(name, CHARINDEX(' ', name) + 1, LEN(name));

如果 CHARINDEX 无法使用,您可以尝试使用任何 SQL 函数来返回 <space> 的索引。请将此视为起点而非复制粘贴的解决方案。

这是一种友善的行为,@theghostofc。感谢您的回答;) - Aleksandr Fedorenko

1
另一种使用CASE表达式的选项。
SELECT CASE WHEN Name LIKE ('%Kumar%') THEN 'Kumar' ELSE 'Prasad' END AS Name, 
       COUNT(*) AS cnt
FROM Student
WHERE Name LIKE  ('%Kumar%')  OR Name LIKE ('%Prasad%')
GROUP BY CASE WHEN Name LIKE ('%Kumar%') THEN 'Kumar' ELSE 'Prasad' END

请参考SQLFiddle上的示例。


0

MySQL 支持正则表达式。

Select Name,count(Name) from Student where Name  REGEXP ('Kumar|Prasad') group by Name  REGEXP ('Kumar|Prasad');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接