日期:2014-05-17 浏览次数:20567 次
declare @t table
( [主键] int,
[客户] nvarchar(8),
[材料] varchar(8),
[数量] float,
[时间] datetime
)
insert into @t
select 1,'水电四局','C30',10.5,'2012-07-01 08:13:23' union all
select 2,'路桥集团','C45',8,'2012-07-01 12:11:23' union all
select 3,'市政建设','C30',12,'2012-07-02 14:33:34'
declare @t2 table
([明细表主键] int ,
[主表主键] int ,
[子项目] nvarchar(16)
)
insert into @t2
select 1,1,'P6' union all
select 2,1,'细石' union all
select 3,1,'塔吊' union all
select 4,2,'P8抗渗' union all
select 5,2,'0-5卵石' union all
select 6,2,'F20' union all
select 7,3,'P8' union all
select 8,3,'细石'
;with t3 as
(
select [客户], [材料],[数量],[子项目]
from @t a inner join @t2 b on a.[主键]= b.[主表主键]
)
select [客户],
max([材料])+stuff((select ''+[子项目] from t3 t where [客户]=t3.[客户] for xml path('')), 1, 1, '') ,
avg([数量]) as [数量]
from t3
group by [客户]
(3 行受影响)
(8 行受影响)
客户 材料 数量
-------- ---------------------------- ----------------------
路桥集团 C458抗渗0-5卵石F20 8
市政建设 C308细石 12
水电四局 C306细石塔吊 10.5
(3 行受影响)
------解决方案--------------------
If not object_id('[tb]') is null
Drop table [tb]
Go
Create table [tb]([col1] int,[col2] int,[col3] int)
Insert tb
Select 2,3,4 union all
Select 2,3,5 union all
Select 2,3,6
Go
--Select * from tb
-->SQL查询如下:
select col1,col2,
stuff((select ','+ltrim(col3) from tb where col1=t.col1 and col2=t.col2 for xml path('')),1,1,'') col3
from tb t
group by col1,col2
--请参考!