我现在查一张表
结果为:班级 考生数 ..... 班主任
1班 50 ..... 张三
1班 50 ..... 李四这样查询出来的东西除了班主任不一样其他都一样的,
我想把结果变为1班 50 ..... 张三、李四这样把最后班主任合并 怎么写呢?
结果为:班级 考生数 ..... 班主任
1班 50 ..... 张三
1班 50 ..... 李四这样查询出来的东西除了班主任不一样其他都一样的,
我想把结果变为1班 50 ..... 张三、李四这样把最后班主任合并 怎么写呢?
select classno,stuNum,stuff((select '、'+classTname from tb where classno = t.classno and stuNum = t.stuNum for xml path('')),1,1,'') as classTname
from tb t
group by classno,stuNum
select tc.f_className1 as 班级,ccsh.f_stunums as 考生数,ccsh.f_subject01Avg as 语文,ccsh.f_allavg as 均分,ccsh.f_threeavg as 三科均分,tt.f_teaname as 班主任 from C_ClassScoreHorizontal as ccsh
left join T_Class as tc on ccsh.f_classguid=tc.f_guid
left join T_Classteacher as tct on tct.f_classguid=ccsh.f_classguid
left join t_teacher as tt on tt.f_guid=tct.f_teaguid
where ccsh.f_examguid='af93d3ea1ace4027afb7f5eecd2cc8ea'忘了说了我是多张表 中间的ccsh.f_subject01Avg as 语文,这类的字段不是固定的 可能会有很多,比如ccsh.f_subject02Avg as 数学, 等等你的sql从 for xml 就看不懂了 那个1,1,‘’是列数吗? 我的列数是不固定的
谢谢你的帮助
;with cte as
(
select tc.f_className1 as 班级,ccsh.f_stunums as 考生数,
ccsh.f_subject01Avg as 语文,ccsh.f_allavg as 均分,ccsh.f_threeavg as 三科均分,
tt.f_teaname as 班主任
from C_ClassScoreHorizontal as ccsh
left join T_Class as tc on ccsh.f_classguid=tc.f_guid
left join T_Classteacher as tct on tct.f_classguid=ccsh.f_classguid
left join t_teacher as tt on tt.f_guid=tct.f_teaguid
where ccsh.f_examguid='af93d3ea1ace4027afb7f5eecd2cc8ea'
)select f_className1,f_stunums,
stuff((select '、'+f_teaname
from cte
where f_className1 = t.f_className1
and f_stunums = t.f_stunums for xml path(''))
,1,1,'') as f_teaname
from cte t
group by f_className1,f_stunums
exp2:替换的起始位置
exp3:需要替换的字符数
exp4:需要替换成的字符或字符串
create table tb
(班级 nvarchar(10),考生数 int,班主任 nvarchar(10))
insert tb
select '1班', 50,'张三' union all
select '1班', 50,'李四' union all
select '2班', 40,'张三2' union all
select '2班', 40,'李四2' union all
select '2班', 40,'王五2' union all
select '3班', 52,'李四3'create function GetStr(@class nvarchar(10))returns nvarchar(500)
as
begin
declare @str as nvarchar(500)
set @str=''
select @str=@str+'、'+班主任 from tb where 班级=@class
return stuff(@str,1,1,'')
endselect 班级,考生数,dbo.GetStr(班级) as 班主任S from tb
班级 考生数 班主任
---------- ----------- ------------------
1班 50 张三、李四
1班 50 张三、李四
2班 40 张三2、李四2、王五2
2班 40 张三2、李四2、王五2
2班 40 张三2、李四2、王五2
3班 52 李四3
select f_className1,f_stunums,
和
group by f_className1,f_stunums
列名无效
select id,name 姓名 from tb
与
select id,name as 姓名 from tb
等价.