--假若生成一个临时表的内容如下:select 'A' sc1,'04-13' sc2,'500' sc3 into #tmp1 union all 
select 'A' sc1,'04-14' sc2,'400' sc3 union all 
select 'B' sc1,'04-12' sc2,'100' sc3 union all 
select 'A' sc1,'04-15' sc2,'700' sc3 union all 
select 'B' sc1,'04-11' sc2,'200' sc3 union all 
select 'B' sc1,'04-13' sc2,'600' sc3 union all 
select 'B' sc1,'04-19' sc2,'800' sc3select * from #tmp1 order by sc1, sc2drop table #tmp1/*
#tmp1显示内容如下
----------------
sc1, sc2,   sc3
A 04-13 500
A 04-14 400
A 04-15 700
B 04-11 200
B 04-12 100
B 04-13 600
B 04-19 800
----------------
-----------------------------------------------
--我想要从临时表#tmp1中生成如下的显示结果:
-----------------------------------------------
sc1, sc4
A 04-13,500; 04-14,400; 04-15,700
B 04-11,200; 04-12,100; 04-13,600; 04-19,800
-----------------------------------------------
请问:这个SELECT 语句如何写。
*/

解决方案 »

  1.   

    http://community.csdn.net/Expert/topic/5470/5470210.xml?temp=.4010431不知是不是也是这个效果?
      

  2.   

    select 'A' sc1,'04-13' sc2,'500' sc3 into #tmp1 union all 
    select 'A' sc1,'04-14' sc2,'400' sc3 union all 
    select 'B' sc1,'04-12' sc2,'100' sc3 union all 
    select 'A' sc1,'04-15' sc2,'700' sc3 union all 
    select 'B' sc1,'04-11' sc2,'200' sc3 union all 
    select 'B' sc1,'04-13' sc2,'600' sc3 union all 
    select 'B' sc1,'04-19' sc2,'800' sc3
    create table #tb 
    (
    sc1 varchar(10),
    sc2 varchar(50)
    )
    go
    declare @sc1 varchar(10)
    declare @re varchar(50)
    set @re =''
    DECLARE cur CURSOR FOR 
    select distinct sc1 from #tmp1
    OPEN cur
    FETCH cur into @sc1
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SELECT @re=@re+' '+sc2+','+sc3+';' FROM #tmp1 WHERE sc1=@sc1
    insert into #tb values (@sc1,STUFF(@re,1,1,''))
    set @re =''
    FETCH cur into @sc1
    END
    CLOSE cur
    DEALLOCATE cur
    select * from #tb
    drop table #tb
    drop table #tmp1
    --结果
    sc1        sc2
    ---------- --------------------------------------------------
    A          04-13,500; 04-14,400; 04-15,700;
    B          04-12,100; 04-11,200; 04-13,600; 04-19,800;(2 行受影响)
    --要是实表用一函数就可以了。
      

  3.   

    CREATE FUNCTION dbo.f_str(@col1 varchar(10))
    RETURNS varchar(100)
    AS
    BEGIN
    DECLARE @re varchar(100)
    SET @re=''
    SELECT @re=@re+' '+sc2+','+sc3+';'
    FROM #tmp1
    WHERE sc1=@col1
    RETURN(STUFF(@re,1,1,''))
    END
    GO
    将#tmp1换成实表名
    select sc1,dbo.f_str(sc1) as sc2 from #tmp1
      

  4.   

    TO: hrb2008()
    非常感谢。1、自定义函数的方法,我以前有用过,因为这里是临时表,所以不能用。
    2、游标的方法是可以了,我试过。再次感谢,但好象听说游标的速度不是很快,并且占内存,不知道还有没有别的更好的方法?