1

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

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

现在我想要输出为

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

4 回答 4

1

你总是有配对的,不多不少?

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
于 2012-08-08T06:40:38.067 回答
0

使用此解决方案:

SELECT list(col2, ':') as col2 FROM table_name group by col1 ;

于 2014-10-19T16:24:16.973 回答
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

检查这里了解如何使用它们。

于 2012-04-16T09:15:39.367 回答
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       
于 2019-04-23T02:01:40.377 回答