22,209
社区成员
发帖
与我相关
我的任务
分享
---创建字符连接函数---
create function [dbo].[f_str](@code int)
returns varchar(50)
as
begin
declare @s varchar(800)
select @s=isnull(@s+' ','')+ltrim(数量)
from tb
where 内码=@code
return @s
end
go
---查询---
select
内码,
名称,
数量=dbo.f_str(内码),
单位,
类别
from tb t
group by 内码,名称,单位,类别
---结果---
内码 名称 数量 单位 类别
----------- ----------- -------------------------------------------------- ---- -----------
1921 钢绞线7/2.2 16.1 16.2 16.3 16.4 吨 2
1923 钢绞线7/2.6 1.0 1.5 吨 2
(2 行受影响)
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([内码] int,[名称] varchar(11),[数量] numeric(3,1),[单位] varchar(2),[类别] int)
insert [tb]
select 1921,'钢绞线7/2.2',16.1,'吨',2 union all
select 1923,'钢绞线7/2.6',1.0,'吨',2 union all
select 1921,'钢绞线7/2.2',16.2,'吨',2 union all
select 1921,'钢绞线7/2.2',16.3,'吨',2 union all
select 1921,'钢绞线7/2.2',16.4,'吨',2 union all
select 1923,'钢绞线7/2.6',1.5,'吨',2
---查询---
select
内码,
名称,
数量=(select ' '+ltrim(数量) from tb where 内码=t.内码 for xml path('')),
单位,
类别
from tb t
group by 内码,名称,单位,类别
---结果---
内码 名称 数量 单位 类别
----------- ----------- -------------------------------------------------- ---- -----------
1921 钢绞线7/2.2 16.1 16.2 16.3 16.4 吨 2
1923 钢绞线7/2.6 1.0 1.5 吨 2
(2 行受影响)