SQL分组统计的有关问题

SQL分组统计的问题
有张表如下 有字段AA(vachar) 字段BB(int)
AA                 BB
--------------------------------
hh879          10
hh98             20
hhh123        10
hhh87           20
hh                 50
dd986         68
cc                 80
ad               90
add98        10
234             20
874             70
=================================================
现在要通过统计汇总做到这样的结果:
hz   sm
------------------------------
hh   80
hhh 30
dd   68
cc    80
ad   90
add  10
234   20
874    70
===================================
请问大家这样的怎么实现?



------解决方案--------------------
引用:
Quote: 引用:

试试这个:

create table t(AA varchar(20),BB int)


insert into t
select 'hh879',          10 union all
select 'hh98',             20 union all
select 'hhh123',        10 union all
select 'hhh87',           20 union all
select 'hh',                 50 union all
select 'dd986',         68 union all
select 'cc',                 80 union all
select 'ad',               90 union all
select 'add98',        10 union all
select '234',             20 union all
select '874',             70
go

select aa,SUM(BB) bb
from 
(
select case when (AA like '%[0-9]%' and AA not like '%[a-z]%') OR
                 (AA not like '%[0-9]%' and AA like '%[a-z]%')
                 then AA
            else left(aa,patindex('%[0-9]%',aa)-1)
       end aa,
       BB            
from t
)t
group by aa
/*
aa bb
234 20
874 70
ad 90
add 10
cc 80
dd 68
hh 80
hhh 30
*/


对上面的数据很完美,但是还有种这种数据 
比如 hh32a,hh-67 ,hh-67a,hh-67-aa ,之类的数据 这种需要归类到hh
这种正则怎么弄呢


再替换一下就行了:

create table t(AA varchar(20),BB int)


insert into t
select 'hh-67',          10 union all
select 'hh-67a',             20 union all
select 'hhh123a',        10 union all
select 'hhh-87-aa',           20 union all
select 'hh',                 50 union all
select 'dd986',         68 union all
select 'cc',                 80 union all
select 'ad',               90 union all
select 'add98',        10 union all
select '234',             20 union all
select '874',             70
go

select replace(aa,'-','') aa,SUM(BB) bb
from 
(
select case when (AA like '%[0-9]%' and AA not like '%[a-z]%') OR
                 (AA not like '%[0-9]%' and AA like '%[a-z]%')