打个比方
主表数据:
主键 客户 材料 数量 时间
1 水电四局 C30 10.5 2012-07-01 08:13:23
2 路桥集团 C45 8 2012-07-01 12:11:23
3 市政建设 C30 12 2012-07-02 14:33:34
细表数据:
细表主键 主表主键 子项目
1 1 P6
2 1 细石
3 1 塔吊
4 2 P8抗渗
5 2 0-5卵石
6 2 F20
7 3 P8
8 3 细石
如何把数据统计成如下样子
名称 数量
C30P6细石塔吊 10.5
C45P8抗渗0-5卵石F20 8
C30P8细石 12
------解决方案--------------------
- SQL code
declare @t table ( [主键] int, [客户] nvarchar(8), [材料] varchar(8), [数量] float, [时间] datetime)insert into @tselect 1,'水电四局','C30',10.5,'2012-07-01 08:13:23' union allselect 2,'路桥集团','C45',8,'2012-07-01 12:11:23' union allselect 3,'市政建设','C30',12,'2012-07-02 14:33:34' declare @t2 table ([明细表主键] int , [主表主键] int , [子项目] nvarchar(16))insert into @t2select 1,1,'P6' union allselect 2,1,'细石' union allselect 3,1,'塔吊' union allselect 4,2,'P8抗渗' union allselect 5,2,'0-5卵石' union allselect 6,2,'F20' union allselect 7,3,'P8' union allselect 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 t3group 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
--请参考!