日期:2014-05-17  浏览次数:20579 次

一个sql查询合并记录数据问题
各位师兄,请教一个问题

一个表:course

字段有:name credit

数据: 英语1 50
  英语2 30
  英语3 20
  物理1 50
  物理2 20
  化学 40


请教如何写查询语句得到下面结果:
name credit

英语1、2、3 100
物理1、2 70
化学 40
   
也就是把三条name包含“英语”的记录(英语1,英语2,英语3)合成一条记录(英语1、2、3)且credit的值为三条记录的credit值之和(50+30+20=100);二条name包含“物理”的记录(物理1,物理2)合成一条记录且credit的值为二条记录的credit值之和(50+20=70);其余的不变。


------解决方案--------------------
SQL code

create table course
(name varchar(16), credit int)

insert into course
select '英语1', 50 union all
select '英语2', 30 union all
select '英语3', 20 union all
select '物理1', 50 union all
select '物理2', 20 union all
select '化学', 40 union all
select '形势与政治1', 50 union all
select '形势与政治2', 40


with t as
(select case isnumeric(right(name,1))
        when 1 then left(name,len(name)-1) 
        else name end 'subjectname',
 name,credit from course
)
select a.subjectname+
       stuff((select '、'+replace(name,a.subjectname,'') from t b
              where b.subjectname=a.subjectname for xml path('')),1,1,'') 'name',
sum(a.credit) 'credit'
from t a
group by a.subjectname
order by a.subjectname desc;

/*
name               credit
------------------ -----------
英语1、2、3           100
形势与政治1、2         90
物理1、2              70
化学                    40

(4 row(s) affected)
*/