在SQL中合并两行,只有一列不同

时间:2017-06-14 22:50:20

标签: sql join union

假设我有一个包含以下信息的表:

FK | Field1 | Field2
---+--------+--------
4  | 103    | 5836
4  | 103    | 5835

FK | Field1 | Field2 | Field2A
---+--------+--------+--------
4  | 103    | 5836   | 5835

由于

1 个答案:

答案 0 :(得分:0)

我认为你真的需要PIVOT,但对于问题中的确切数据集,你可以按照下面的方法,它有点奇怪,在T-SQl中:

declare @a as int
declare @b as int
declare @c as int
declare @query Varchar(Max)

set @query = 'Select 4,103'
DECLARE curs CURSOR FOR   
select * From
(select 4 as a , 103 as b   , 5836 as c
Union select 4 as a , 103 as b   , 5835 as c) as res

OPEN curs  

FETCH NEXT FROM curs   
INTO @a,@b,@c
WHILE @@FETCH_STATUS = 0  
BEGIN 
set @query = @query + ','+cast(@c as varchar)

FETCH NEXT FROM curs   
INTO @a,@b,@c

END
CLOSE curs;  
DEALLOCATE curs;
EXEC(@query)