当前位置: 代码迷 >> Sql Server >> 新年好!sql合并字段的有关问题!
  详细解决方案

新年好!sql合并字段的有关问题!

热度:19   发布时间:2016-04-24 18:34:36.0
新年好!sql合并字段的问题!!急!!!
现在还苦逼的坐在电脑前码代码的相信不止我一个人!!!!
问题如下:
table1  字段1  字段2  字段3
          1      5      1
          1      2      1
          2      3      1
          3      4      1
我要合并成这样,然后插入到另外一个空表里去
table   字段1   字段2
          1      7
          2      3 
          3      4
我写的sql如下:
insert into table2 (字段1,字段2) select 字段1 as 字段1,sum(字段2)as 字段2 from table1 where
字段3=1 group by 字段1   
不知道各位大虾看明白没,就是根据字段1分组来合并字段2,字段3是个条件。。。。。我对group by不是很理解,第一次这样写,结果跟我想的差很远!!! 求大虾指教!求正确的sql和为什么错了。
哎,祝各位大虾新年快乐。。。。我下班了。。。。。回去了在给分好不。。。。  
------解决方案--------------------
这个语句:

insert into table2 (字段1,字段2) 
select 字段1 ,sum(字段2)as 字段2 
from table1 
where 字段3=1 
group by 字段1  

看着你的语句并没有什么错误呀
------解决方案--------------------
楼主的语句结果应该同以上相同

不明白你错那里?

------解决方案--------------------
你写的好像没什么问题:

create table table1(字段1 int, 字段2 int,  字段3 int)

insert into table1
select 1      ,5      ,1 union all
select 1      ,2      ,1 union all
select 2      ,3      ,1 union all
select 3      ,4      ,1

create table table2(字段1 int,字段2 int)
go


insert into table2 (字段1,字段2) 
select 字段1 ,sum(字段2) as 字段2 
from table1 
where 字段3=1 
group by 字段1


select * from table2
/*
字段1 字段2
1 7
2 3
3 4
*/

------解决方案--------------------
--> --> 
 
declare @T table([字段1] int,[字段2] int,[字段3] int)
Insert @T
select 1,5,1 union all
select 1,2,1 union all
select 2,3,1 union all
select 3,4,1


select 
字段1 as 字段1,sum(字段2)as 字段2 from @T where
字段3=1 group by 字段1   
/*
字段1 字段2
1 7
2 3
3 4
*/

------解决方案--------------------
还是这样?

--> --> 
 
declare @T table([字段1] int,[字段2] int,[字段3] int)
Insert @T
select 1,5,1 union all
select 1,2,1 union all
select 2,3,1 union all
select 3,4,1


select 
字段1 as 字段1
,stuff((select ','+rtrim(字段2) from @T where [字段1]=a.[字段1] for xml path('')),1,1,'') as 字段2 
from @T as a
where 字段3=1 group by 字段1   

/*
字段1 字段2
1 5,2
2 3
3 4
*/

------解决方案--------------------
create table table1 (字段1 int, 字段2 int, 字段3 int)
insert into table1 values(1,5,1),(1,2,1),(2,3,1),(3,4,1)
select *from table1

select 字段1,sum(字段2)字段2,sum(字段3)字段3 from table1 group by 字段1

不知道这是楼主要的结果么?
  相关解决方案