--如果goods固定只有4個
Select
id,
visit,
Max(Case goods When 1 Then name Else Null End) As goods1,
Max(Case goods When 2 Then name Else Null End) As goods2,
Max(Case goods When 3 Then name Else Null End) As goods3,
Max(Case goods When 4 Then name Else Null End) As goods4
From

Group By
id,
visit

解决方案 »

  1.   


    --動態
    declare @str varchar(1000)
    set @str='select id,visit '
    select @str=@str+',min(case when goods='''+goods+''' then nane else '' end) as '''+goods+''''
    from t group by goods
    select @str=@str+' from t group by id,visit'
    exec(@str)
      

  2.   

    id    表示用户
      visit 表示反问次数 
      goods 表示发生顺序
      mame  表示发生 物品名称id     visit   goods   name
    196 1 1 衣服
    196 1 2 裤子
    196 1 3 帽子
    196 2 1 鞋
    196 2 2 袜子
    196 2 3 皮带
    196 2 4 衣服
    566 1 1 钢笔
    566 2 1 啤酒
    566 3 1 螺丝刀
                                    
                                
     变成下表                                    
                                                         
    id     visit     goods1     goods2  goods3  goods4
    196 1  衣服 裤子 帽子 NULL
    196 2 鞋 袜子 皮带 衣服
    566 1 钢笔 NULL NULL NULL
    566 2 啤酒 NULL NULL NULL
    566 3 螺丝刀 NULL NULL NULL
      

  3.   

    語句有兩處筆誤,幫你修改下。--動態
    declare @str varchar(1000)
    set @str='select id,visit '
    select @str=@str+',min(case when goods='''+goods+''' then name else '''' end) as '''+goods+''''
    from t group by goods
    select @str=@str+' from t group by id,visit'
    exec(@str)
      

  4.   

    或者--動態
    declare @str varchar(1000)
    set @str='select id,visit '
    select @str=@str+',min(case when goods='''+goods+''' then name else Null end) as '''+goods+''''
    from t group by goods
    select @str=@str+' from t group by id,visit'
    exec(@str)
      

  5.   

    star1083(),什麼意思?代碼寫的有問題嗎?
      

  6.   

    重新发一下..刚刚的没有发清楚........paoluo(一天到晚游泳的鱼)  goods不是固定的哦....需要交叉查以后看谁 领的东西最多.fa_ge(鶴嘯九天)   动态的还看不懂...呵呵!
       
    谢谢楼上的兄弟了. 我看了.自己在试试....
      

  7.   

    我还不知道..我马上回家做一下.告诉你...fa_ge(鶴嘯九天) 现在下班了!
      

  8.   

    paoluo(一天到晚游泳的鱼)
      虽然我没有写 动态的
      我开始的时候用静态的写了一下。。也是遇到这个问题!
    “varchar 值 cname else Null end) as '' 转换为数据类型为 int 的列时发生语法错误。”   googs 是INT  我把结构改成 VARCHAR 就可以了!! 谢谢 paoluo(一天到晚游泳的鱼) !和 fa_ge(鶴嘯九天)   谢谢你们了哦!
      

  9.   

    --動態
    declare @str varchar(1000)
    set @str='select id,visit '
    select @str=@str+',min(case when goods='''+ Cast(goods As Varchar) +''' then name else Null end) as goods'''+ Cast(goods As Varchar) +''''
    from t group by goods
    select @str=@str+' from t group by id,visit'
    exec(@str)