id     test    Rank
1       hello   1
1       i       2
1       am      3
1       king     4
2       i        1
2       am       2
2        the     3
2        best    4一句sql查询如下结果:
id     test    
1       hello i am king 
1       i am the best

解决方案 »

  1.   

    更正:一句sql查询如下结果:
    =======================================
    id     test    
    1       hello i am king 
    2       i am the best强烈歉意
      

  2.   

    select distinct id,'hello i am king' from table where id =1 union
    select distinct id,'i am the best' from table where id = 2
      

  3.   

    --和行转列的应用效果差不多了,统计结果中可能会用到
    --测试表
    create table Test
    (id varchar(10),
     Test varchar(10),
     rank int)
    --插入数据
    insert into Test 
    select '1' ,'hello',1 
    union
    select '1' ,'i' ,2
    union
    select '1' ,'am' ,3
    union
    select '1' ,'king' ,4
    union
    select '2' ,'i' ,1
    union
    select '2' ,'m' ,2
    union
    select '2' ,'the' ,3
    union
    select '2' ,'best' ,4
    --一条动态SQL语句go
    --合并函数
    CREATE FUNCTION MergeCharField(@id varchar(255))
    RETURNS varchar(8000)
    AS
    BEGIN
    DECLARE @r varchar(8000)
    SET @r=''
    SELECT @r=@r+' '+rtrim(Test) FROM Test WHERE id=@id
    order by rank
    RETURN(@r)
    END
    GO
    --调用
    select  id,dbo.MergeCharField(id)as text from test group by id
    --删除测试环境
    drop table test
    drop FUNCTION MergeCharField/*
    1  hello i am king
    2  i m the best*/
      

  4.   

    还是刚刚的表select *
    from(
        select distinct 
            id
        from Test
    )a
    outer apply(
        select 
            test= stuff(REPLACE(REPLACE(
                (
                    SELECT test FROM test n
                    where id = A.id order by rank
                    for xml auto 
                ), '<n test="', ' '), '"/>', ''), 1, 1, ''))n
      

  5.   

    jinjazz(近身剪) 谢谢了
    ============================
    谁还能抛出一条sql2000下的
      

  6.   

    create function roy(@i int)
    returns varchar(4000)
    as
    begin
    declare @v varchar(400),@s varchar(400)
    set @v=''select @v=@v+test from **
    where id=@i
    set @v=left(@v,len(@v)-1)
    return @v
    end
      

  7.   

    sql2000只能用我的第一种方法,必须用自定义函数来实现
      

  8.   

    有一句sql能搞定的吗???
    ---------------------------
    sql 2k 好像没有,需要套一个函数sql 2k5 目前不清楚昨天刚回答了一个同样的需求:
    http://community.csdn.net/Expert/TopicView3.asp?id=5603231