日期:2014-05-18  浏览次数:20543 次

SQL 语句 在线等 就是按UID把 KEY列里面的值 用 / 连接起来
CREATE TABLE #Table ( 
[ID] [int] IDENTITY(1,1) NOT NULL,
[UID] [int] ,
[key] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
)  
GO 
--drop table #Table
insert into #Table
select 1,'A,B' union all 
select 1,'C,D' union all 
select 2,'B,C,D' union all 
select 1,'B' union all 
select 2,'C' union all 
select 2,'D' 

要求结果:  

 UID KEYS
 1 'A,B/C,D/B/'
 2 'B,C,D/C/D/' 

就是按UID把 KEY列里面的值 用 / 连接起来 

谢谢


------解决方案--------------------
自己写个函数,,,
------解决方案--------------------
create function getAA(@Uid int)
returns varchar(1000)
as
begin
declare @sql varchar(1000)
select @sql=isnull(@sql+'/','')+[key] from [Table] where uid=@uid order by id
returns @sql
end

go 
select uid,dbo.getAA(uid) keys from [Table] group by uid
------解决方案--------------------
SQL code
 
CREATE  TABLE  #Table  ( 
[ID] [int] IDENTITY(1,1) NOT NULL,
[UID] [int] ,
[key] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL,

GO 
--drop table #Table
insert  into  #Table
select  1, 'A,B ' union  all 
select  1, 'C,D ' union  all 
select  2, 'B,C,D ' union  all 
select  1, 'B ' union  all 
select  2, 'C ' union  all 
select  2, 'D '

select uid,[key]=cast([key] as varchar(1000))  into # from #table order by uid
declare @col1 varchar(100),@col2 varchar(1000)
update # set @col2=case when @col1=uid then @col2+'/'+[key] else [key] end, @col1=uid,[key]=@col2
select uid,[key]=max([key]) from # group by uid
drop table #


结果
-----------
uid key
1 A,B /C,D /B 
2 C /D /B,C,D