select 
    ID,名称,
    max(case 属性 when '保质期' then 值 end) as 保质期,
    max(case 属性 when '出产日期' then 值 end) as 出产日期
from 
    表 
group by 
    ID,名称

解决方案 »

  1.   

    select ID,min(名称),max(case when 属性='保质期' then 值 else null end) as 保质期,max(case when 属性='出产日期' then 值 else null end) as 出产日期 from 表 group by id
      

  2.   

    declare @t table(ID int,名称 varchar(10),属性 varchar(10),值 varchar(10))
    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
    */
      

  3.   

    select ID,名称,Max(case  when 属性 = 保质期 then 值 else '' end),Max(case  when 属性 = 出产日期 then 值 else '' end)
    from Table group by ID,名称
    没有测试过,不知道得不得
      

  4.   

    declare @sql varchar(8000)
    select @sql=@sql+',max(case when 属性='''+属性+''' then 值 else null end) as '+属性 from 表 group by 属性
    exec('select ID,min(名称)'+@sql+' from 表 group by id')
      

  5.   

    create table #t (ID int,名称 varchar(10),属性 varchar(10),值 varchar(10))
    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
      

  6.   

    上面那个漏了set @sql =''初始化
      

  7.   

    create table test(ID int,名称 varchar(10),属性 varchar(10),值 varchar(10))
    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