表1
ID NAM N1 N2 N3
001 AAA 80 0 0
表2
ID NAM N1 N2 N3
001 AAA 0 50 0
表3
ID NAM N1 N2 N3
001 AAA 0 0 30
我用union all 合并后
ID NAM N1 N2 N3
001 AAA 80 0 0
001 AAA 0 50 0
001 AAA 0 0 30
我想要的 结果是
ID NAM N1 N2 N3
001 AAA 80 50 30 这个应该是 合并成一条记录
------解决方案--------------------
- SQL code
select ID,NAM,max(N1) N1,max(N2) N2,max(N3) N3from (你union all后的结果) tgroup by t.ID,t.NAM;
------解决方案--------------------
- SQL code
--> 测试数据:@表1declare @表1 table([ID] varchar(3),[NAM] varchar(3),[N1] int,[N2] int,[N3] int)insert @表1select '001','AAA',80,0,0--> 测试数据:@表2declare @表2 table([ID] varchar(3),[NAM] varchar(3),[N1] int,[N2] int,[N3] int)insert @表2select '001','AAA',0,50,0--> 测试数据:@表3declare @表3 table([ID] varchar(3),[NAM] varchar(3),[N1] int,[N2] int,[N3] int)insert @表3select '001','AAA',0,0,30SELECT ID,NAM,MAX(N1) N1,MAX(N2) N2,MAX(N3) N3 FROM ( SELECT * FROM @表1 UNION ALL SELECT * FROM @表2 UNION ALL SELECT * FROM @表3)T GROUP BY ID,NAM/*ID NAM N1 N2 N3---- ---- ----------- ----------- -----------001 AAA 80 50 30*/