--如果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
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
--動態
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)
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
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)
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)
谢谢楼上的兄弟了. 我看了.自己在试试....
虽然我没有写 动态的
我开始的时候用静态的写了一下。。也是遇到这个问题!
“varchar 值 cname else Null end) as '' 转换为数据类型为 int 的列时发生语法错误。” googs 是INT 我把结构改成 VARCHAR 就可以了!! 谢谢 paoluo(一天到晚游泳的鱼) !和 fa_ge(鶴嘯九天) 谢谢你们了哦!
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)