使用group by查找计数

时间:2013-06-25 09:27:37

标签: sql sql-server

我有一张学生表,如下所示

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>的索引。

  

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

答案 2 :(得分: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

上的示例

答案 3 :(得分:0)

Mysql支持regexp。

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