select
ID,名称,
max(case 属性 when '保质期' then 值 end) as 保质期,
max(case 属性 when '出产日期' then 值 end) as 出产日期
from
表
group by
ID,名称
ID,名称,
max(case 属性 when '保质期' then 值 end) as 保质期,
max(case 属性 when '出产日期' then 值 end) as 出产日期
from
表
group by
ID,名称
insert into @t select 1,'面包 ','保质期 ','1个月 '
insert into @t select 1,'面包 ','出产日期','2005.01.01'
insert into @t select 2,'矿泉水','保质期 ','6个月 '
insert into @t select 2,'矿泉水','出产日期','2006.05.06'select
ID,名称,
max(case 属性 when '保质期' then 值 end) as 保质期,
max(case 属性 when '出产日期' then 值 end) as 出产日期
from
@t
group by
ID,名称/*
ID 名称 保质期 出产日期
----------- ---------- ---------- ----------
2 矿泉水 6个月 2006.05.06
1 面包 1个月 2005.01.01
*/
from Table group by ID,名称
没有测试过,不知道得不得
select @sql=@sql+',max(case when 属性='''+属性+''' then 值 else null end) as '+属性 from 表 group by 属性
exec('select ID,min(名称)'+@sql+' from 表 group by id')
insert into #t select 1,'面包 ','保质期 ','1个月 '
insert into #t select 1,'面包 ','出产日期','2005.01.01'
insert into #t select 2,'矿泉水','保质期 ','6个月 '
insert into #t select 2,'矿泉水','出产日期','2006.05.06'declare @sql varchar(8000)
set @sql =''
select @sql=@sql+',max(case when 属性='''+属性+''' then 值 else null end) as '+属性 from #t group by 属性print @sql
exec('select ID,min(名称)'+@sql+' from #t group by id')------
1 面包 1个月 2005.01.01
2 矿泉水 6个月 2006.05.06
insert into test select 1,'面包 ','保质期 ','1个月 '
insert into test select 1,'面包 ','出产日期','2005.01.01'
insert into test select 2,'矿泉水','保质期 ','6个月 '
insert into test select 2,'矿泉水','出产日期','2006.05.06'
godeclare @sql varchar(8000)
set @sql =''select @sql=@sql+',['+属性+']=max(case when 属性='''+属性+''' then 值 else null end) '
from test group by 属性set @sql='select ID,名称'+@sql+' from test group by id,名称'exec(@sql)
go/*
ID 名称 保质期 出产日期
----------- ---------- ---------- ----------
2 矿泉水 6个月 2006.05.06
1 面包 1个月 2005.01.01
*/
drop table test
go