【问题标题】:find the count using group by使用 group by 查找计数
【发布时间】:2013-06-25 09:27:37
【问题描述】:

我有一个学生表如下

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 ???

【问题讨论】:

标签: sql sql-server


【解决方案1】:
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。谢谢你的回答,+1;)
    【解决方案3】:

    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上的示例

    【讨论】:

      【解决方案4】:

      Mysql 支持正则表达式。

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

      【讨论】:

        猜你喜欢
        • 2020-01-19
        • 2014-07-02
        • 1970-01-01
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多