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

4 回答 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
于 2013-06-25T09:31:14.320 回答
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>.

请将此视为起点,而不是复制粘贴解决方案。

于 2013-06-25T09:39:42.207 回答
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上的示例

于 2013-06-25T09:44:40.710 回答
0

Mysql 支持正则表达式。

Select Name,count(Name) from Student where Name  REGEXP ('Kumar|Prasad') group by Name  REGEXP ('Kumar|Prasad');
于 2014-01-06T10:19:11.693 回答