在sybase中,我需要将行值转换为varchar类型的单个列

问题描述 投票:1回答:4

你能给我一个查询,它将varchars类型的行值转换为带有任何分隔符的单个列。例如,有2列的表

col1 |col2
1 | m10
1 | m31
2 | m20
2 | m50

现在我想输出为

col1| col2
1|m10:m31
2|m20:m50
sybase-ase
4个回答
0
投票

一种方法是使用游标。

使用光标,您可以一次获取一行!

伪代码将是:

if actual_col1 = last_col1
then col2_value = col2_value + actual_col2
else
insert into #temptable value(col1, col2_value)
col2_value = actual_col2
end

检查HERE以了解如何使用它们。


0
投票

你总是有配对,不多也不少吗?

select
  col1,
  count(*)
from table
group by col1
having count(*) <> 2

会给你零结果吗?

如果是这样,你可以自己加入......

declare @delimiter varchar(1)

set @delimiter = :

select
t1.col1, t1.col2 + @delimiter + t2.col2
from tablename t1
inner join tablename t2
  on t1.col1 = t2.col1
  and t1.col2 <> t2.col2

0
投票

使用此解决方案:

SELECT列表(col2,':')作为col2 FROM table_name group by col1;


0
投票

请使用下面的逻辑,表#t1将是决赛桌。

create table #t123(a char(2), b char(2))        
go       
create table #t1(a char(2), c char(100)  default '')       
go       
Insert into #t123 values ('a','1')       
Insert into #t123 values ('a','2')       
Insert into #t123 values ('a','3')       
Insert into #t123 values ('b','1')       
Insert into #t123 values ('c','1')       
Insert into #t123 values ('d','1')       
Insert into #t123 values ('d','1')       
go       
insert into #t1 (a) Select distinct a from #t123       
go       
Select distinct row_id = identity(8), a into #t1234 from #t123       
go       
Declare @a int, @b int, @c int, @d int, @e int, @f char(2), @g char(2), @h char(2)       
Select @a =min(row_id), @b=max(row_id) from #t1234       
While @a <= @b       
Begin       
Select @f = a , @h = '', @g = '' from #t1234 where row_id = @a       
Update #t1 set c = '' where a = @f       

Select row_id = identity(8), b into #t12345 from #t123 where a = @f       
Select @c =min(row_id), @d=max(row_id) from #t12345       
While @c <= @d       
begin       
Select @g = b from #t12345 where row_id = @d       
Update #t1 set c = @g +'     '+ c  where a = @f --change delimiter       
Select @d = @d-1       
End       

Drop table #t12345       
Select @a = @a+1       

End       
go       
Select * from #t1 -- final table with transposed values       
© www.soinside.com 2019 - 2024. All rights reserved.