Mytable: UserID options
9126 aa^0|bb^1|cc^0|13^0|12^0|11^0
9126 aa^0|bb^0|cc^0|13^1|12^0|11^0
9126 aa^0|bb^0|cc^0|13^0|12^0|11^1
9129 aa^0|bb^0|cc^0|13^0|12^0|11^0
9130 aa^0|bb^0|cc^0|13^0|12^0|11^0
         ……
用select options from Mytable where UserID='9126' 假设取得
aa^0|bb^1|cc^0|13^0|12^0|11^0
aa^0|bb^0|cc^0|13^1|12^0|11^0
aa^0|bb^0|cc^0|13^0|12^0|11^1那么比较多条记录,^1的值优先返回,上面的例子返回: aa^0|bb^1|cc^0|13^1|12^0|11^1
不知道描述的是否清楚,请高手指点一下。

解决方案 »

  1.   

    create table t(UserID int,options varchar(40))
    insert into t 
    select 9126,'aa^0|bb^1|cc^0|13^0|12^0|11^0' union all
    select 9126,'aa^0|bb^0|cc^0|13^1|12^0|11^0' union all
    select 9126,'aa^0|bb^0|cc^0|13^0|12^0|11^1' union all
    select 9129,'aa^0|bb^0|cc^0|13^0|12^0|11^0' union all
    select 9130,'aa^0|bb^0|cc^0|13^0|12^0|11^0'
    gocreate function f_str(@UserID int)
    returns varchar(40)
    as
    begin
        declare @ret varchar(40)
        select 
            @ret=
            MAX(PARSENAME(replace(left(options,19) ,'|','.'),4))+'|'+
            MAX(PARSENAME(replace(left(options,19) ,'|','.'),3))+'|'+
            MAX(PARSENAME(replace(left(options,19) ,'|','.'),2))+'|'+
            MAX(PARSENAME(replace(right(options,19),'|','.'),3))+'|'+
            MAX(PARSENAME(replace(right(options,19),'|','.'),2))+'|'+
            MAX(PARSENAME(replace(right(options,19),'|','.'),1))
        from t where UserID=@UserID
        group by UserID
        return @ret
    end
    go
    select UserID,dbo.f_str(UserID) options from t where UserID=9126 group by UserID
    /*
    UserID      options                                  
    ----------- ---------------------------------------- 
    9126        aa^0|bb^1|cc^0|13^1|12^0|11^1
    */
    godrop function f_str
    drop table t
    go
      

  2.   

    我的意思就是说 :
    条件:
    options 字段的值是由多个如aa^0结构的元素组成,假设aa是元素的名称,0、1是元素的值
    目标:
    将多条记录合并成一条记录
    合并原则:
    如果在任意一条记录中aa的值为1,那么就aa的值就是1,同理其他的元素;最后将各元素仍以"|"分隔返回。例如:
    aa^0|bb^1|cc^0|13^0|12^0|11^0
    aa^0|bb^0|cc^0|13^1|12^0|11^0
    aa^0|bb^0|cc^0|13^0|12^0|11^1
    返回: aa^0|bb^1|cc^0|13^1|12^0|11^1