1,建自定义函数
Create function getstr(@id Nchar(100))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(4000),@分隔符 Nvarchar(10)
set @分隔符=N','
set @str=N''
select @str=@str+rtrim(Col)+@分隔符 from 表名
--------------------------------^^^^要相加的字段名
where 相加条件字段=@id
set @str=left(@str,len(@str)-1)落 ---却除最后一个分隔符
return @str
end
GO2,调用
select 条件字段,dbo.getstr(条件字段) from 表名 group by 条件字段
Create function getstr(@id Nchar(100))
returns Nvarchar(4000)
as
begin
declare @str Nvarchar(4000),@分隔符 Nvarchar(10)
set @分隔符=N','
set @str=N''
select @str=@str+rtrim(Col)+@分隔符 from 表名
--------------------------------^^^^要相加的字段名
where 相加条件字段=@id
set @str=left(@str,len(@str)-1)落 ---却除最后一个分隔符
return @str
end
GO2,调用
select 条件字段,dbo.getstr(条件字段) from 表名 group by 条件字段
--创建数据合并的函数:
Create function f_merg(@卡号 varchar(100),@部门 varchar(100),@日期 datetime)
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+' '+时间 from 表 where 卡号=@卡号 and 部门=@部门 and 日期=@日期
set re=substring(@re,2,8000)
return(@re)
end
GO--调用此函数实现你的要求:
select 卡号,部门,日期,时间=dbo.f_merg(卡号,部门,日期) from 表 group by 卡号,部门,日期
from so_contract a,so_contract_prod b,product c
where a.so_contract_id=b.so_contract_id and b.prod_id=c.prod_id and (a.state=(select max(approver_step) from process_function,approve_process
where process_function.approver_id=approve_process.approver_id and process_function.table_name='so_contract'))
set @c=0
update #aaa set @a=case when @b=so_contract_id then @a else '' end+时间+',',
@c=case when @b=so_contract_id then @c else @c+1 end,@b=so_contract_id,gr=@c,value=@aselect max(so_contract_id) as so_contract_id,max(value) result into #bbb from #aaa group by gr
select a.so_contract_id,(select sum(total) from #aaa ) as total,a.so_contract_date,a.delivery_date,a.prod_id,b.result as prod_type
from #aaa a,#bbb b
where a.so_contract_id=b.so_contract_id and a.value=b.result
drop table #aaa
drop table #bbb