select top 5 left(name,2),count(left(name,2))
from table1
group by left(name,2)
order by count(left(name,2)) desc

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :DBA_Huangzj(發糞塗牆)
    -- Date    :2014-01-02 13:26:31
    -- Version:
    --      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
    -- Dec 28 2012 20:23:12 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
    --
    ----------------------------------------------------------------
    --> 测试数据:[table1]
    if object_id('[table1]') is not null drop table [table1]
    go 
    create table [table1]([id] int,[name] varchar(6))
    insert [table1]
    select 1,'pa2323' union all
    select 2,'wa1232' union all
    select 3,'ya9823' union all
    select 4,'mn2342' union all
    select 5,'pa1232' union all
    select 6,'ui1232'
    --------------开始查询--------------------------
    select top 5 left(name,2) '以字母开头',count(left(name,2)) '数量'
    from table1
    group by left(name,2)
    order by count(left(name,2)) desc
    ----------------结果----------------------------
    /* 
    以字母开头 数量
    ----- -----------
    pa    2
    ya    1
    wa    1
    ui    1
    mn    1
    */
      

  2.   


    版主你太牛逼了,谢谢,非常感谢,我还不知道left可以这么用呢!!!大大的好人
      

  3.   

    select top 5
           substring(name,1,2) as name,
           COUNT(*) cc
    from table1
    group by substring(name,1,2)
    order by count(*) desc
      

  4.   

    如果取1个字母,酒吧left后面的2改成1。