日期:2014-05-16  浏览次数:20729 次

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