表A  ID  TYPEID  QTY
  A001  A     2
  A002  B     3
  A003  C     5
  變成
  ID   A   B   C  
  A001 2   3   5

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(小F,向高手学习)
    -- Date    :2011-03-16 15:01:58
    -- Verstion:
    --      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
    -- Nov 24 2008 13:01:59 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([ID] varchar(4),[TYPEID] varchar(1),[QTY] int)
    insert [tb]
    select 'A001','A',2 union all
    select 'A002','B',3 union all
    select 'A003','C',5
    --------------开始查询--------------------------
    select
       'a001',
       max(case typeid when 'a' then qty else '' end) as 'A',
       max(case typeid when 'B' then qty else '' end) as 'B',   
       max(case typeid when 'C' then qty else '' end) as 'C'
    from
       tb
    ----------------结果----------------------------
    /*      A           B           C
    ---- ----------- ----------- -----------
    a001 2           3           5(1 行受影响)
    */
      

  2.   

    寫錯了,都是A001
    表A  ID TYPEID QTY
      A001 A 2
      A001 B 3
      A001 C 5
       變成
      ID A B C   
      A001 2 3 5
      

  3.   

    select
       ITEMID,thk_inventd2id,thk_inventd3id,thk_inventd4id,thk_inventdgoldtypeid,
       max(case typeid when 'ProdImgS' then pic else '' end) as 'ProdImgS',
       max(case typeid when 'Osketch' then pic else '' end) as 'Osketch',   
       max(case typeid when 'Dsketch' then pic else '' end) as 'Dsketch'
      from #caryfindata2
      group by 
      ITEMID,thk_inventd2id,thk_inventd3id,thk_inventd4id,thk_inventdgoldtypeid上樓寫得不錯,但我發現如果GROUP那里除了ITEMID,如果其他4個有空值的話,結果就不對了
      

  4.   

    select
       id,
       max(case typeid when 'a' then qty else '' end) as 'A',
       max(case typeid when 'B' then qty else '' end) as 'B',   
       max(case typeid when 'C' then qty else '' end) as 'C'
    from
       tb
    group y
       id