交叉表的问题!鱼鱼师傅不知道在不在???? 帮忙解决一下
create table table_goods (id varchar(10),visit int,goods_id varchar(10),goods int ,name varchar(30))
insert table_goods
select '196' , 1 , 'a01', 1 ,'衣服'
union all select '196' , 1 , 'a02', 2 , '裤子'
union all select '196' , 1 , 'a03', 3 , '帽子'
union all select '196' , 2 , 'a04', 1 , '鞋'
union all select '196' , 2 , 'a05', 2 , '袜子'
union all select '196' , 2 , 'a06', 3 , '皮带'
union all select '196' , 2 , 'a07', 4 , '衣服'
union all select '566' , 1 , 'b08', 1 , '钢笔'
union all select '566' , 2 , 's09', 1 , '啤酒'
union all select '566' , 3 , 'g01', 1 , '螺丝刀'
id 表示用户
visit 表示反问次数
goods_id 表示发生物品ID
goods 表示发生顺序
mame 表示发生 物品名称
id visit goods_id goods cname
196 1 a01 1 衣服
196 1 a02 2 裤子
196 1 a03 3 帽子
196 2 a04 1 鞋
196 2 a05 2 袜子
196 2 a06 3 皮带
196 2 a07 4 衣服
566 1 b08 1 钢笔
566 2 s09 1 啤酒
566 3 g01 1 螺丝刀
变成下表
id visit goods_id1 goods1 goods_id2 goods2 goods_id3 goods3 goods_id4 goods4
196 1 a01 衣服 a02 裤子 a03 帽子 NULL NULL
196 2 a04 鞋 a05 袜子 a06 皮带 a07 衣服
566 1 b08 钢笔 NULL NULL NULL NULL NULL NULL
566 2 s09 啤酒 NULL NULL NULL NULL NULL NULL
566 3 g01 螺丝刀 NULL NULL NULL NULL NULL NULL
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)
-- 这里的goods 是 INT 但是 name 是VARCHAR 这里的 cast(goods as varchar) 类型转换会出错 现在如果在加一列 goods_id 该怎么写啊?
求动态语句 和 静态语句 的写法。。。。我在这里先 谢谢了!!